https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Moritz Post

11/12/2021, 11:30 AM
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

Klitos Kyriacou

11/12/2021, 2:07 PM
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

Moritz Post

11/12/2021, 2:44 PM
thanks for the answer. that is a valid option.
p

Paul Griffith

11/12/2021, 5:12 PM
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

Klitos Kyriacou

11/12/2021, 5:20 PM
Indeed. Assuming it's a random-access list, of course.
1
2 Views