hello i have a list of numbers in the range 1-255....
# getting-started
m
hello i have a list of numbers in the range 1-255. how could i transform these numbers into a
ByteArray
? a direct conversion via
byteArrayOf
does not work since the numbers are unsigned but
ubyteArrayOf
does also not work for a reason i don't fully understand. It would be possible to map each number to
it - 128
but that seams a bit unefficient. Help would be appreciated.
k
The following will transform into a byteArray such that values between 128 and 255 will be negative (using 2's complement):
Copy code
val list = listOf(0, 1, 80, 127, 128, 255, 256)
    val bytes = list.map { it.toByte() }.toByteArray()
    println(bytes.contentToString())
m
thanks for the answer. that is a valid option.
p
Copy code
val bytes = ByteArray(list.size) { list[it].toByte() }
is probably more efficient than the above; the ByteArray() pseudo-constructor is treated specially by the compiler
1
k
Indeed. Assuming it's a random-access list, of course.
1