Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Jon Avadis
Ranch Hand
Posts: 49
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20608
63
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Jon Avadis
Ranch Hand
Posts: 49
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Rob for that thorough explanation!
 
Rob Spoor
Sheriff
Pie
Posts: 20608
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic