Search code examples
javabyteunsignedsigned

Convert unsigned byte to signed byte


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 + 11110000) = 32bits), how can I get the signed value for this int?


Solution

  • 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.