Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# Please explain to me a line of code in a method that converts bytes to Hex-Values?

Ranch Hand
Posts: 49
Hi guys

I found this method that converts Byte Arrays to a hexadecimal value as String.
I understand the code, except for the following line:

I suppose its some kind of bit-transformation, but how exactly does this convert the byte
into an int ranging from 1 to 16?

Heres the full code

Rob Spoor
Sheriff
Posts: 20495
54
• 1
A byte has just 8 bits. An int has 32. When a byte is cast to an int the missing 24 bits are filled with the byte's sign bit, for instance:
1111 0000 (-16) is turned into 1111 1111 1111 1111 1111 1111 1111 0000, because the sign bit (the left one) is 1.
0111 0000 (112) is turned into 0000 0000 0000 0000 0000 0000 0111 0000, because the sign bit (the left one) is 0.

0xFF is the same as 0000 0000 0000 0000 0000 0000 1111 1111. When the & is applied, it basically takes the byte's value, adds all the zeros or ones, and then turns all those added zeros / ones into zeros, and keeping the bits of the original byte. The result is the same value as the byte had when it was not negative, and the value of the byte + 256 if it was negative. The result is a number between 0 and 255 (inclusive), instead of a number between -128 and 127 (inclusive).