简体   繁体   English

将带符号字节数组转换为整数数组

[英]Convert Signed Byte Array to Int array

I have an integer array 我有一个整数数组

int res[] = {176, 192, 312, 1028, 1064, 1016};

I get the signed byte array of the corresponding int array like this 我得到了这样的相应int数组的有符号字节数组

int signed_byte_array[] = {-80, 0, -64, 0, 56, 1, 4, 4, 40, 4, -8, 3};

Each index in the int array is represented by two indexes in the byte array, means each value in int array is represented as 2 bytes. int数组中的每个索引由字节数组中的两个索引表示,这意味着int数组中的每个值均表示为2个字节。

I don't have access to the int array and I want to convert this signed byte array exactly to the int array 我无权访问int数组,并且我想将此带符号的字节数组完全转换为int数组

How can I do this? 我怎样才能做到这一点?

Thanks 谢谢

It appears that the bytes represent unsigned 16-bit integers, with the most significant byte coming second, and the bits above 8-th truncated. 看起来这些字节代表无符号的16位整数,其中最高有效字节排在第二位,而第8位以上的位被截断。 You can do the conversion like this: 您可以像这样进行转换:

int[] signed_byte_array = {-80, 0, -64, 0, 56, 1, 4, 4, 40, 4, -8, 3};
int[] int_array = new int[signed_byte_array.length / 2];
for (int i = 0 ; i != int_array.length ; i++) {
    int_array[i] = (signed_byte_array[2*i+1] & 0xFF) << 8
                 | (signed_byte_array[2*i+0] & 0xFF);
}

When I added printing of int_array[i] in the loop I got these values: 当我在循环中添加int_array[i]打印时,我得到了以下值:

176 192 312 1028 1064 1016
private static int[] toB(int[] res) {
    int[] bytes = new int[res.length * 2];
    for (int i = 0; i < res.length; ++i) {
        int value = res[i];
        int lo = value & 0xFF;
        int hi = (value >> 8) & 0xFF;
        bytes[2 * i] = (int)(byte) lo;
        bytes[2 * i + 1] = (int)(byte) hi;
    }
    return bytes;
}

private static int[] toI(int[] bytes) {
    int[] res = new int[bytes.length / 2];
    for (int i = 0; i < res.length; ++i) {
        int lo = (int) bytes[2 * i] & 0xFF;
        int hi = (int) bytes[2 * i + 1] & 0xFF;
        res[i] = lo | (hi << 8);
    }
    return res;
}

public static void main(String[] args) {
    int[] res = {176, 192, 312, 1028, 1064, 1016};
    int[] signed_byte_array = {-80, 0, -64, 0, 56, 1, 4, 4, 40, 4, -8, 3};
    System.out.println("b: " + Arrays.toString(toB(res)));
    System.out.println("i: " + Arrays.toString(toI(signed_byte_array)));
}

gives

b: [-80, 0, -64, 0, 56, 1, 4, 4, 40, 4, -8, 3]
i: [176, 192, 312, 1028, 1064, 1016]

It is evidently a short[] to byte[] conversion. 显然,这是从short []到byte []的转换。 As you have an int[] I would say, there exists no utility conversion function. 就像您说的是int []一样,不存在实用程序转换功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM