1. 2个字节数组转换为整数
1 def bytes2uint8(_bytes: Array[Byte], _offset: Int): Int = { 2 val b0 = _bytes(_offset) & 0xff 3 return b0 4 } 5 6 def bytes2sint8(_bytes: Array[Byte], _offset: Int): Int = { 7 val b0 = _bytes(_offset) 8 return b0 9 }
2. 4个字节数组转换为整数
1 def bytes2uint16(_bytes: Array[Byte], _offset: Int): Int = { 2 var b0 = _bytes(_offset) & 0xff 3 var b1 = _bytes(_offset + 1) & 0xff 4 5 return ((b1 << 8) | b0).toShort & 0x0FFFF 6 } 7 8 //需要添加import java.nio.ByteBuffer 9 def bytes2sint16(_bytes: Array[Byte], _offset: Int): Int = { 10 var _array: Array[Byte] = new Array[Byte](2) 11 _array(0) = _bytes(_offset + 1) 12 _array(1) = _bytes(_offset) 13 return ByteBuffer.wrap(_array).getShort() 14 }
3. 8个字节数组转换为整数
1 def bytes2uint32(_bytes: Array[Byte], _offset: Int): Long = { 2 var b0 = _bytes(_offset + 0) & 0xff 3 var b1 = _bytes(_offset + 1) & 0xff 4 var b2 = _bytes(_offset + 2) & 0xff 5 var b3 = _bytes(_offset + 3) & 0xff 6 return ((b3 << 24) | (b2 << 16) | (b1 << 8) | b0).toLong & 0xFFFFFFFFL 7 } 8 9 def bytes2sint32(_bytes: Array[Byte], _offset: Int): Int = { 10 var b0 = _bytes(_offset) & 0xff 11 var b1 = _bytes(_offset + 1) & 0xff 12 var b2 = _bytes(_offset + 2) & 0xff 13 var b3 = _bytes(_offset + 3) & 0xff 14 return ((b3 << 24) | (b2 << 16) | (b1 << 8) | b0) 15 }
4. 2个字节数组转换为布尔型(Bool)
1 def bytes2bool(_bytes: Array[Byte], _offset: Int): Boolean = { 2 var b0 = _bytes(_offset) & 0xff 3 var b1 = _bytes(_offset + 1) & 0xff 4 5 return if (((b1 << 8) | b0) != 0) true else false 6 }
5. 4个字节数组转换为浮点型(Float)
1 import java.nio.ByteBuffer 2 def bytes2float(_bytes: Array[Byte], _offset: Int): Double = { 3 4 var _array: Array[Byte] = new Array[Byte](4) 5 6 for (i <- 0 until 4) { 7 _array(i) = _bytes(-i + _offset + 3) 8 } 9 10 return ByteBuffer.wrap(_array).getFloat() 11 }
6. 8个字节数组转换为Double
1 import java.nio.ByteBuffer 2 def bytes2real(_bytes: Array[Byte], _offset: Int): Double = { 3 4 var _array: Array[Byte] = new Array[Byte](8) 5 6 for (i <- 0 until 8) { 7 _array(i) = _bytes(-i + _offset + 7) 8 } 9 10 return ByteBuffer.wrap(_array).getDouble 11 }
7. 8个字节数组转换为Long
1 import java.nio.ByteBuffer 2 def bytes2long(_bytes: Array[Byte], _offset: Int): Double = { 3 var _array: Array[Byte] = new Array[Byte](8) 4 5 for (i <- 0 until 8) { 6 _array(i) = _bytes(-i + _offset + 7) 7 } 8 return ByteBuffer.wrap(_array).getLong 9 }