将有符号字节数组转换为无符号字节

将有符号字节数组转换为无符号字节

问题描述:

我有一个字节数组.

bytes[] = [43, 0, 0, -13, 114, -75, -2, 2, 20, 0, 0]

我想将其转换为Java中的无符号字节.这就是我所做的:创建一个新数组,并使用&复制值.0xFF:

I want to convert it to unsigned bytes in Java. this is what I did: created a new array and copy the values with & 0xFF:

    this.bytes = new byte[bytes.length];
    for (int i=0;i<bytes.length;i++)
        this.bytes[i] = (byte) (bytes[i] & 0xFF);

,但是值在新数组中也保持负数.我在做什么错了?

but the values stay negative in the new array as well. what am I doing wrong?

bytes 在Java中总是经过签名的.

bytes in Java are always signed.

如果要获取这些字节的无符号值,可以将它们存储在 int 数组中:

If you want to obtained the unsigned value of these bytes, you can store them in an int array:

byte[] signed = {43, 0, 0, -13, 114, -75, -2, 2, 20, 0, 0};
int[] unsigned = new int[signed.length];
for (int i = 0; i < signed.length; i++) {
    unsigned[i] = signed[i] & 0xFF;
}

您将获得以下值:

[43, 0, 0, 243, 114, 181, 254, 2, 20, 0, 0]