Handle unsigned byte in Java

Java does not support unsigned byte. But it is needed for some situations. One 

example is UTF-8 encoding. One solution to this problem is to bitwise and the 

byte.

 

// encoding byte for 0x80
byte b = -128;

/*
 * 0xff is a integer literal. So 0xff and b need to converted to integer before 
 * doing the bitwise and. 0x80 is converted into 0xffffff80. Then 0xff & 
 * 0xffffff80. The result is 0x80 which is an integer.
 */
int result = 0xff & b;
 

你可能感兴趣的:(java)