base 16
Saturday, July 28, 2018
7:50 AM
8down voteaccepted
Hexadecimal is base 16, so instead of counting from 0 to 9, we count from 0 to F. And we generally prefix hex constants with 0x. Thus,
Hex      Dec
-------------
0x00  =  0
0x09  =  9
0x0A  =  10
0x0F  =  15
0x10  =  16
0x200 =  512
A byte is the typical unit of storage for values on a computer, and on most all modern systems, a byte contains 8 bits. Note that bit actually means binary digit, so from this, we gather that a byte has a maximum value of 11111111 binary. That is 0xFF hex, or 255 decimal. Thus, one byte can be represented by a minimum of two hexadecimal characters. A typical 4-byte int is then 8 hex characters, like 0xDEADBEEF.
RGB values are typically packed with 3 byte values, in that order, RGB. Thus,
R=255 G=0 B=0    =>  R=0xFF G=0x00 B=0x00  =>  0xFF0000  or #FF0000 (html)
R=66  G=0 B=248  =>  R=0x42 G=0x00 B=0xF8  =>  0x4200F8  or #4200F8 (html)
For my hex calculations, I like to use python as my calculator:
>>> a = 0x427FB
>>> b = 700
>>> a + b
273079
>>>
>>> hex(a + b)
'0x42ab7'
>>>
>>> bin(a + b)
'0b1000010101010110111'
>>>
For the RGB example, I can demonstrate how we could use bit-shifting to easily calculate those values:
>>> R=66
>>> G=0
>>> B=248
>>>
>>> hex( R<<16 | G<<8 | B )
'0x4200f8'
>>>
shareedit
edited Aug 22 '12 at 23:10
redtuna
3,8361532
answered Aug 22 '12 at 21:22
Jonathon Reinhart
85.2k20155219
add a comment
up vote2down vote
Base-16 (also known as hex) notation is convenient because you can fit four bits in exactly one hex digit, making conversion to binary very easy, yet not requiring as much space as a full binary notation. This is useful when you need to represent bit-oriented data in a human-readable form.
Learning hex is easy - all you need to do is memorizing a short table of 16 rows defining hex-to-binary conversion:
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
With this table in hand, you can easily convert hex strings of arbitrary length to their corresponding bit patterns:
0x478FD105 - 01000111100011111011000100000101 
Converting back is easy as well: group your binary digits by four, and use the table to make hex digits
0010 1001 0100 0101 0100 1111 0101 1100 - 0x29454F5C