converting an array of signed bytes to unsigned bytes [duplicate]

烈酒焚心 提交于 2019-12-02 03:22:22

问题


I have a array of bytes.

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

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?


回答1:


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

You'll get the following values:

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



回答2:


Java has no thing called an unsigned byte. You have to use other types like short or int to be able to hold values > 127.



来源:https://stackoverflow.com/questions/46949759/converting-an-array-of-signed-bytes-to-unsigned-bytes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!