在JAVA中将短数组转换为字节数组
我对如何将short
数组转换为byte
数组感到困惑。 例如,我有以下short
arrays
short[] shrt_array = new short[]{ 0x4 , 0xd7 , 0x86, 0x8c, 0xb2, 0x14, 0xc, 0x8b, 0x2d, 0x39, 0x2d, 0x2d, 0x27, 0xcb, 0x2e, 0x79, 0x46, 0x36, 0x9d , 0x62, 0x2c };
通过使用此链接将短数组转换为字节数组这两种转换方法,我得到以下两个不同的byte
数组:
expectedByteArray = new byte[] { (byte) 0x4, (byte) 0xd7, (byte) 0x86, (byte) 0x8c, (byte) 0xb2, (byte) 0x14, (byte) 0xc, (byte) 0x8b, (byte) 0x2d, (byte) 0x39, (byte) 0x2d, (byte) 0x2d, (byte) 0x27, (byte) 0xcb, (byte) 0x2e, (byte) 0x79, (byte) 0x46, (byte) 0x36, (byte) 0x9d, (byte) 0x62, (byte) 0x2c, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte)0x0};
第二个结果:`
expectedByteArray = new byte[] { (byte) 0x4, (byte) 0x0, (byte) 0xd7, (byte) 0x0, (byte) 0x86, (byte) 0x0, (byte) 0x8c, (byte) 0x0, (byte) 0xb2, (byte) 0x0, (byte) 0x14, (byte) 0x0, (byte) 0xc, (byte) 0x0, (byte) 0x8b, (byte) 0x0, (byte) 0x2d, (byte) 0x0, (byte) 0x39, (byte) 0x0, (byte) 0x2d, (byte) 0x0, (byte) 0x2d, (byte) 0x0, (byte) 0x27, (byte) 0x0, (byte) 0xcb, (byte) 0x0, (byte) 0x2e, (byte) 0x0, (byte) 0x79, (byte) 0x0, (byte) 0x46, (byte) 0x0, (byte) 0x36, (byte) 0x0, (byte) 0x9d, (byte) 0x0, (byte) 0x62, (byte) 0x0, (byte) 0x2c, (byte) 0x0};
`
你能帮助我哪一个是正确的吗?
你使用asShortBuffer
有点接近。 它应该是:
ByteBuffer buffer = ByteBuffer.allocate(shrt_array.length * 2); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.asShortBuffer().put(shrt_array); byte[] bytes = buffer.array();
手动执行此操作以显式控制字节顺序:
byte[] tobytes(short[] shorts, boolean bigendian) { int n = 0; byte[] bytes = new byte[2*shorts.length]; for (n=0; n < shorts.length; n++) { byte lsb = shorts[n] & 0xff; byte msb = (shorts[n] >> 8) & 0xff; if (bigendian) { bytes[2*n] = msb; bytes[2*n+1] = lsb; } else { bytes[2*n] = lsb; bytes[2*n+1] = msb; } } return bytes; }
如果s
是短值,则具有s & 0xff
最低有效字节和最高有效字节为(s >> 8) & 0xff
。 您可以按所需顺序将它们放在字节数组索引2*n
和2*n+1
中,其中n
是short数组中的索引。