How to Convert Int to Unsigned Byte and Back

前端 未结 10 653
死守一世寂寞
死守一世寂寞 2020-11-28 23:04

I need to convert a number into an unsigned byte. The number is always less than or equal to 255, and so it will fit in one byte.

I also need to convert that byte ba

10条回答
  •  失恋的感觉
    2020-11-28 23:48

    A byte is always signed in Java. You may get its unsigned value by binary-anding it with 0xFF, though:

    int i = 234;
    byte b = (byte) i;
    System.out.println(b); // -22
    int i2 = b & 0xFF;
    System.out.println(i2); // 234
    

提交回复
热议问题