What is the best way to work around the fact that ALL Java bytes are signed?

后端 未结 7 1155
误落风尘
误落风尘 2020-12-02 12:29

In Java, there is no such thing as an unsigned byte.

Working with some low level code, occasionally you need to work with bytes that have unsigned values greater tha

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 12:53

    When reading any single value from the array copy it into something like a short or an int and manually convert the negative number into the positive value it should be.

    byte[] foobar = ..;
    int value = foobar[10];
    if (value < 0) value += 256 // Patch up the 'falsely' negative value
    

    You can do a similar conversion when writing into the array.

提交回复
热议问题