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

后端 未结 7 1172
误落风尘
误落风尘 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:36

    The best way to do bit manipulation/unsigned bytes is through using ints. Even though they are signed they have plenty of spare bits (32 total) to treat as an unsigned byte. Also, all of the mathematical operators will convert smaller fixed precision numbers to int. Example:

    short a = 1s;
    short b = 2s;
    int c = a + b; // the result is up-converted
    short small = (short)c; // must cast to get it back to short
    

    Because of this it is best to just stick with integer and mask it to get the bits that you are interested in. Example:

    int a = 32;
    int b = 128;
    int foo = (a + b) | 255;
    

    Here is some more info on Java primitive types http://mindprod.com/jgloss/primitive.html

    One last trivial note, there is one unsigned fixed precision number in Java. That is the char primitive.

提交回复
热议问题