Bitwise operation on byte type
Byte type is one of the important typesin Java. It is 8 bit long and is a signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type are often used in low level data processing ( could be audio data processing etc). They do save memory.
However, bitwise operation on byte type creates issues. Consider the following simple code snipped that is expected to bitwise AND two byte variables and produce the output in byte.
|
However, If you compile and run this program, you will get following compile error.
error: possible loss of precision z = x & y; // Bitwise AND x and y ^ required: byte found: int 1 error |
The Java compiler throws error because it upconverts any byte to int type before it applies any bitwise operation. The int type is 32 bits long ( 4 times that of the byte type). The solution to this problem is to declare z as int type.
int z ;
So basically, when you compute
z = x & y ;
x and y are upconverted to integer before bitwise AND operation is applied. Finally, it is a good idea to AND x and y with 0xFF and also the result with 0xFF.
|