Convert unsigned byte to signed byte

前端 未结 5 1880
抹茶落季
抹茶落季 2020-12-17 21:37

Is there an easy and elegant way to convert an unsigned byte value to a signed byte value in java? For example, if all I have is the int value 240 (in binary (24 bits + 1111

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-17 22:04

    Here's how to store and convert an unsigned byte value:

    byte b = (byte) 144; // binary value = 10010000
    

    If you cast b to an int here's what happens:

    int i = b;
    System.out.println("value: "+i);  
    System.out.println("binary: " + Integer.toBinaryString(i));
    

    Output:

    value: -112 <- Incorrect value
    binary: 11111111111111111111111110010000 
    

    Why does this happen? Bytes are signed in Java, and b is negative so the cast operation fills the resulting int with 1s from the left. More on java data formats.

    So how do we get back from -112 to the correct value of 144? We need a 32-bit bitmask, which we can create with an int:

    int mask = 0x000000FF; // This is often shortened to just 0xFF
    

    Now we can use the bitwise & operator to "zero out" the left most 24 bits, leaving only our original 8 bits.

    int unsignedValue = b & mask; // value = 144
    

    Our original value of 144 has been restored and can be safely cast back to a byte:

    byte original = (byte) unsignedValue;
    

提交回复
热议问题