Convert unsigned byte to signed byte

前端 未结 5 1839
抹茶落季
抹茶落季 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 21:46
    public int getUnsignedByte(byte[] bytes, int offset) {
        return (bytes[offset] & 0xFF);
    }
    

    should do the work.

    0 讨论(0)
  • 2020-12-17 21:59

    Java does not have unsigned values, except for char. Consider this snippet:

    byte val = (byte)255;
    System.out.println(String.valueOf(val));
    

    The result will be -1, because the lowest 8 bits got copied over to the byte variable.

    0 讨论(0)
  • 2020-12-17 22:02

    In Java all the primitive types, except for char, are signed. You can't have an unsigned byte. The only thing you may do is to cast the unsigned byte to an int so you can read its proper value:

    int a = b & 0xff
    

    If you want to store an unsigned byte value in a byte type, you obviously can, but every time you need to "process" it, just remember to cast it again as showed above.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-17 22:07

    Java only supports signed bytes so whenever you place a value in a byte, its assumed to be signed.

    byte b = (byte) 240;
    

    However if you want to store an unsigned byte, you need to handle this yourself. (i.e. Java doesn't support it but you can do it)

    For operations like +, -, *, <<, >>>, ==, !=, ~ you don't need to change anything, For operations like <, > you need to have make minor adjustments, and for operations like /, % you need to use a larger data type.

    A common alternative is to use a larger data type like int to store values 0 - 255. There is not much disadvantage in doing so.

    0 讨论(0)
提交回复
热议问题