views:

843

answers:

4

I was looking over this code to calculate math.sqrt in Java. I was just wondering why they used hex values in some of the loops and as normal values for variables. What benefits are there to use hex?

Thanks for your help.

+3  A: 

They probably used hex values because the numbers are easier to remember in hex. For example, 0x7fffffff is the same as 2147483647, but is a lot easier to remember.

Nate879
+22  A: 

Because hex corresponds much more closely to bits that decimal numbers. Each hex digit corresponds to 4 bits (a nibble). So, once you've learned the bitmask associated with each hex digit (0-F), you can do something like "I want a mask for the low order byte":

0xff

or, "I want a mask for the bottom 31 bits":

0x7fffffff

Just for reference:

HEX    BIN
0   -> 0000
1   -> 0001
2   -> 0010
3   -> 0011
4   -> 0100
5   -> 0101
6   -> 0110
7   -> 0111
8   -> 1000
9   -> 1001
A   -> 1010
B   -> 1011
C   -> 1100
D   -> 1101
E   -> 1110
F   -> 1111
Dave Ray
+1  A: 

You can represent very large numbers very concisely with hex values since you can fit 6 more values in each digit.

I personally like to use hex when I'm dealing with colors, since I'm used to hex-color-codes from CSS. Example: new Color(0xee, 0xff, 0xee), which would be equivalent to the HTML color-code #eeffee and is much more readable to me than new Color(238, 255, 238).

Zach Langley
+1  A: 

Hex is a human readable form of the binary the CPU actually uses. When looking at low level commands it often makes more sense to match the CPU and think in hex,

Jim C