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

Oha*_*had 3 java unsigned

我有一个字节数组。

bytes[] = [43, 0, 0, -13, 114, -75, -2, 2, 20, 0, 0]
Run Code Online (Sandbox Code Playgroud)

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

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

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

Era*_*ran 8

bytes in Java are always signed.

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;
}
Run Code Online (Sandbox Code Playgroud)

You'll get the following values:

[43, 0, 0, 243, 114, 181, 254, 2, 20, 0, 0]
Run Code Online (Sandbox Code Playgroud)


Lot*_*har 1

Java 没有所谓的无符号字节。您必须使用其他类型,例如shortorint才能保存大于 127 的值。