4

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.

Bharat DEVre
  • 539
  • 3
  • 13
  • 1
    Answers on the following question might be useful, http://stackoverflow.com/questions/11380062/what-does-value-0xff-do-in-java – Anthony Forloney Dec 24 '15 at 13:35
  • It's a bitwise operator - the top answer at stackoverflow.com/questions/17256644/how-does-the-bitwise-and-work-in-java does a pretty good job of explaining what it is – xuanji Dec 24 '15 at 13:35
  • `getBytes()` probably is not returning ASCII codes. Evaluate [Charset.defaultCharset()](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#defaultCharset--) to find out which character set and encoding is the default for your system. – Tom Blodget Dec 24 '15 at 14:22

2 Answers2

1

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

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
ParkerHalo
  • 4,341
  • 9
  • 29
  • 51