programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

Hex Conversion

Mike Cunningham
Ranch Hand
Posts: 130
What is the easiest using paper and a pencil to find the answer to the following question.
Question:
What is the result of the following fragment of code?
(byte)0x81>>2
The mock exam says the answer is: 0xFFFFFFE0
However, when I compile and run, the answer is:
-32

Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
You should do a search in this forum since this kind of questions have been heavily discussed.
Here is an interesting resource about how numbers are represented in binary: http://www.javaranch.com/campfire/StoryBits.jsp
The short answer is that the cast to byte only applies to 0x81.
The binary representation of 0x81 is 00000000 00000000 00000000 10000001.
When you cast it to byte, you get 10000001 (that is you only keep the low-level byte). Then, the latter is converted to int again since the right-hand operand of the >> operator is an int. When you do this conversion you have to keep the sign (left-most bit) which yields 11111111 11111111 11111111 10000001. Then we right-shift the latter 2 positions to the right and we get 11111111 11111111 11111111 11100000 which is 0xFFFFFFE0.

Mike Cunningham
Ranch Hand
Posts: 130
Thanks for the explanation. It helped alot. I've read the campfire story before...it's helpful on getting a good general understanding of bit shifting. I think this example included a few concepts that were not covered there.
So, I guess I got the -32 based on adding up the converted & shifted bits and then tacking on a negative 1.
And then...to go from
11111111 11111111 11111111 11100000
to
0xFFFFFFE0
Do I just match up the #'s in sections of 4? 1111=F, 1110=E, etc. Is that the correct way to figure the Hex value?
- Mike

Rob Ross
Bartender
Posts: 2205
Yes, that's it. binary and hex are related like that because they are both powers of two: four binary digits to one hex digit.

Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
You got it right Mike...
To go from binary to hexadecimal just group the bits by 4 and then translate as follows:
binary => hexa
0000 => 0
0001 => 1
0010 => 2
0011 => 3
0100 => 4
0101 => 5
0110 => 6
0111 => 7
1000 => 8
1001 => 9
1010 => A
1011 => B
1100 => C
1101 => D
1110 => E
1111 => F
If you want to know exactly why this is the way it is, you should search a little bit for threads about that topic since there has been excellent explanations in some discussions...