This week's book giveaway is in the OCP forum.We're giving away four copies of OCP Java SE 8 Programmer II Exam Study Guide and have Kathy Sierra, Bert Bates, & Elizabeth Robson on-line!See this thread for details.
Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# 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

Sheriff
Posts: 21289
87
• 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).