我想从Kotlin中的两个字节创建一个UInt16值.这是我想出来的:
fun BytesToUInt16(b1 : Byte, b2 : Byte) : UInt {
val uInt16Value = ((b1.toUShort() shl 8) or (b2.toUShort())
return uInt16Value
}
但在Kotlin ,用shl转换UInt16似乎是不可能的. 从两个字节创建UInt16的正确方法是什么?
我想从Kotlin中的两个字节创建一个UInt16值.这是我想出来的:
fun BytesToUInt16(b1 : Byte, b2 : Byte) : UInt {
val uInt16Value = ((b1.toUShort() shl 8) or (b2.toUShort())
return uInt16Value
}
但在Kotlin ,用shl转换UInt16似乎是不可能的. 从两个字节创建UInt16的正确方法是什么?
希望这个能帮上忙!
//BytesToUInt16
//I have two bytes
fun bytesToUInt16(byte1: Byte, byte2: Byte): Int {
return ((byte1.toInt() and 0xFF) shl 8) or (byte2.toInt() and 0xFF)
}
//create a byte
val byte1: Byte = 0b11111111.toByte()
val byte2: Byte = 0b11111111.toByte()
val result = bytesToUInt16(byte1, byte2)
println(result) // 65535
//// 258
val byte3: Byte = 0b00000001.toByte()
val byte4: Byte = 0b00000010.toByte()
val result2 = bytesToUInt16(byte3, byte4)
println(result2) // 258