JAVA中短数组到字节数组的转换

JAVA中短数组到字节数组的转换,java,byte,bytearray,short,Java,Byte,Bytearray,Short,我对如何将短数组转换为字节数组感到困惑。 我有下面的短数组 通过使用这两种转换方法的链接,我得到了以下两种不同的字节数组: 第二个结果:` 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, (

我对如何将短数组转换为字节数组感到困惑。 我有下面的短数组

通过使用这两种转换方法的链接,我得到了以下两种不同的字节数组:

第二个结果:`

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};
`

你能告诉我哪一个是正确的吗。

你对“混蛋”的使用有点接近。应该是:

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是短数组中的索引。

您所说的右是什么意思?这取决于你的要求。您是否需要将每个短码转换为单个字节,例如忽略前8位或转换为两个字节的值?我必须将每个短码转换为字节。约翰指出的是,短数组的每个值都是两个字节。请看@student-以什么顺序排列?最高有效字节优先,还是最低有效字节优先?
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;
}