#kotlin #kotlin-native
#kotlin #kotlin-native
Вопрос:
Как преобразовать ByteArray в ULong в kotlin.
val byteArray = byteArrayOf(
0, 0, 0, 0,
0, 0, 0, 1
)
Ответ №1:
fun UByteArray.getULongBe() =
((this[7].toULong() and 0xFFu) shl 56) or
((this[6].toULong() and 0xFFu) shl 48) or
((this[5].toULong() and 0xFFu) shl 40) or
((this[4].toULong() and 0xFFu) shl 32) or
((this[3].toULong() and 0xFFu) shl 24) or
((this[2].toULong() and 0xFFu) shl 16) or
((this[1].toULong() and 0xFFu) shl 8) or
(this[0].toULong() and 0xFFu)
fun UByteArray.getULongLe() =
((this[0].toULong() and 0xFFu) shl 56) or
((this[1].toULong() and 0xFFu) shl 48) or
((this[2].toULong() and 0xFFu) shl 40) or
((this[3].toULong() and 0xFFu) shl 32) or
((this[4].toULong() and 0xFFu) shl 24) or
((this[5].toULong() and 0xFFu) shl 16) or
((this[6].toULong() and 0xFFu) shl 8) or
(this[7].toULong() and 0xFFu)
val uByteArray = ubyteArrayOf(
UByte.MAX_VALUE, UByte.MAX_VALUE,
UByte.MAX_VALUE, UByte.MAX_VALUE,
UByte.MAX_VALUE, UByte.MAX_VALUE,
UByte.MAX_VALUE, UByte.MAX_VALUE,
)
ULong.MAX_VALUE
// 18446744073709551615
uByteArray.getULongBe()
// 18446744073709551615
uByteArray.getULongLe()
// 18446744073709551615
val byteArray = byteArrayOf(
0, 0, 0, 0,
0, 0, 0, 1
)
byteArray.toUByteArray().getULongLe()
// 1
byteArray.toUByteArray().getULongBe()
// 72057594037927936