jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes Please explain to me a line of code in a method that converts bytes to Hex-Values? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Please explain to me a line of code in a method that converts bytes to Hex-Values?" Watch "Please explain to me a line of code in a method that converts bytes to Hex-Values?" New topic
Author

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

Jon Avadis
Ranch Hand

Joined: Jul 20, 2011
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



Knowledge Reigns Supreme
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19693
    
  20

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).


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Jon Avadis
Ranch Hand

Joined: Jul 20, 2011
Posts: 49

Thanks a lot Rob for that thorough explanation!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19693
    
  20

You're welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Please explain to me a line of code in a method that converts bytes to Hex-Values?