Search code examples
javaimage-processingintbyte

How to convert int to byte in Java?


I have this integer in java:

int i = 1067030938;
byte b = (byte) i;

which gives me:

-102

How could I go from b back to i ?


I tried :

b = b & 0xff;

but this gives 154


Solution

  • If you have

    int i = 1067030938;
    

    And just want the low order 8 bits, then do

    i &= 0xff;
    
    System.out.println(i);
    

    Prints

    154
    

    If you want the signed value of converted int then do this

    i = (byte)i; // will be -102