在JAVA中将短整型数组转换为字节数组

4

我不知道如何将short数组转换为byte数组。 例如,我有以下short数组:

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

通过使用这个链接将short数组转换为byte数组,我得到了以下两种不同的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};

你能帮我确定哪一个是正确的。


1
“Right”是什么意思?这取决于您的要求。您需要将每个“short”转换为单个“byte”(例如通过忽略前8位)还是转换为两个“byte”值? - Jon Skeet
1
约翰指出的是,short类型占用两个字节。 - tom
对我来说很清楚,short类型占用两个字节。在我发布的链接中,他们分配了一个字节数组2*short_array.length。这相当于short_array的两倍大小。但我不明白的是,哪一个才是正确的字节数组。 - student
@Fildor,我需要第二种方法,将两个字节添加到字节数组中。 - student
1
@student - 以什么顺序?最重要的字节先还是最不重要的字节先? - Ingo
显示剩余6条评论
2个回答

10

你使用asShortBuffer有些接近了。正确写法应该是:

ByteBuffer buffer = ByteBuffer.allocate(shrt_array.length * 2);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.asShortBuffer().put(shrt_array);
byte[] bytes = buffer.array();

5
手动执行以明确控制字节顺序:
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是一个short值,那么你可以通过s & 0xff得到最低有效字节,通过(s >> 8) & 0xff得到最高有效字节。你可以将它们按照任意顺序放在字节数组的索引2*n2*n+1中,其中n是short数组中的索引。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接