Why use hex values instead of normal base 10 numbers?
Asked Answered
S

3

6

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

Schmo answered 16/1, 2009 at 20:34 Comment(0)
S
28

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
Smithy answered 16/1, 2009 at 20:40 Comment(0)
B
3

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.

Bramble answered 16/1, 2009 at 20:39 Comment(0)
C
2

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,

Christy answered 16/1, 2009 at 20:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.