While converting byte to hex there is use of '&' operator. I want to know what it does?
byte[] b="ABC".getBytes();
System.out.println(b[1] & 0xFF);
It gives output 66 as it is ASCII value of 'B' Any help will be welcome. Thanks.
While converting byte to hex there is use of '&' operator. I want to know what it does?
byte[] b="ABC".getBytes();
System.out.println(b[1] & 0xFF);
It gives output 66 as it is ASCII value of 'B' Any help will be welcome. Thanks.
This code had nothing to do with byte to hex conversion.
b[1]
can be negative, since bytes in Java have values between -128 and 127.
b[1] & 0xFF
forces the output to be parsed as a positive integer.
For example, if b[1]
was equal to -14, b[1] & 0xFF
would give you 242, since the bit-wise AND is performed after the two arguments are promoted to int
type, so when you perform &
with 0xFF
, whose binary representation is 000...00011111111
, you'll always get a positive result.
The &
operator (if used on integer-numbers like byte,short,int,long) is the Logic-AND operator. The logic AND-operator works as it follows:
0 1 1 0 0 1 0 1
& 1 0 1 1 0 0 0 1
-----------------
0 0 1 0 0 0 0 1
It is a bit by bit comparison of the binary notation of the 2 numbers. If both of the bits are 1 it will result in 1, otherwise it will result in 0:
& || 0 | 1 <- a
===========
0 || 0 | 0
===========
1 || 0 | 1
^
b