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.

  1. /*
  2.   ReferenceDesigner.com Tutorial for beginners
  3.   Bitwise operation on byte type
  4.  */
  5. class bitwise{
  6.  
  7. public static void main (String args[]) {
  8. byte x, y;
  9. x = 0x0F;
  10. y = 0x1F;
  11. byte z;
  12. z = x & y; // Bitwise AND x and y
  13. System.out.println("z is " + z); // We expect output to be 0x0F or 15 in decimal
  14. }
  15. }


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.

  1. /*
  2.   ReferenceDesigner.com Tutorial for beginners
  3.   Bitwise operation on byte type
  4.  */
  5. class bitwise1{
  6.  
  7. public static void main (String args[]) {
  8. byte x, y;
  9. x = 0x0F;
  10. y = 0x1F;
  11. int z;
  12. z = ((x & 0xFF) & ( y & 0xFF)) & 0xFF ; // Bitwise AND x and y
  13. System.out.println("z is " + z); // We expect output to be 0x0F or 15 in decimal
  14. }
  15. }