Hi all, I need to initialize a `ByteArray` with he...
# announcements
u
Hi all, I need to initialize a
ByteArray
with hex literals. Here is my Approach:
Copy code
val key = intArrayOf(0x80, 0xFF, 0x00, 0x7f).map { it.toByte() }.toByteArray()
And the result is (and should be):
Copy code
-128,-1,0,127
Is there a more compact/idiomatic way to do that?
Really to bad that this does not work:
Copy code
ubyteArrayOf(0x80, 0xFF, 0x00, 0x7f).toByteArray()
and neither
Copy code
ubyteArrayOf(0x80u, 0xFFu, 0x00u, 0x7fu).toByteArray()
g
I think it would be more efficient to use: toByte on every item
but yeah, byte constants is pain, don’t think that there is perfect solution
personaly I would use:
Copy code
byteArrayOf(0x80.toByte(), 0xFF.toByte(), 0x00, 0x7f)
u
Well @gildor, this was just an example. It gets really ugly when you have a long byte string. So I prefer readability over efficiency here. To me the whole topic is more about style then hard facts :-)
e
Copy code
ubyteArrayOf(0x80u, 0xFFu, 0x00u, 0x7Fu)
can call
.toByteArray()
on that if you need, although it makes a copy
@uli works for me, not sure what you mean by "neither"?
u
i fell into the pit again, I think. IntelliJ EAP does not have a kotlin 1.5.x plugin yet and I was trying in the REPL. So it complained:
Copy code
ubyteArrayOf(0x80u, 0xFFu, 0x00u, 0x7fu).toByteArray()
error: type of the constant expression cannot be resolved. Please make sure you have the required dependencies for unsigned types in the classpath
Fell into the same pit yesterday. I should know by now :-)
c
Intellij stable does handle UInt & Co correctly. Not sure why EAP is behind
u
there is no compatible kotlin 1.5.10 plugin for EAP yet. 1.4.32 is the latest compatible