jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Hex Conversion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Hex Conversion" Watch "Hex Conversion" New topic

Hex Conversion

Mike Cunningham
Ranch Hand

Joined: Nov 14, 2000
Posts: 130
What is the easiest using paper and a pencil to find the answer to the following question.
What is the result of the following fragment of code?
The mock exam says the answer is: 0xFFFFFFE0
However, when I compile and run, the answer is:
Valentin Crettaz
Gold Digger

Joined: Aug 26, 2001
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.

[Blog] [Blogroll] [My Reviews] My Linked In
Mike Cunningham
Ranch Hand

Joined: Nov 14, 2000
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
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

Joined: Jan 07, 2002
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.

SCJP 1.4
Valentin Crettaz
Gold Digger

Joined: Aug 26, 2001
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...
I agree. Here's the link: http://aspose.com/file-tools
subject: Hex Conversion
It's not a secret anymore!