Converting binary to hexadecimal looks like math homework, but it is really just a lookup. Once you know one rule, you can do it in your head.
The rule: group in fours, from the right
A hex digit has 16 possible values, and four bits have exactly 16 patterns (2^4 = 16). So one hex digit stands for one group of four bits.
- Group the bits in fours, starting from the right.
- Pad the leftmost group with zeros if it has fewer than four bits.
- Replace each group with its hex digit (0-9, then A-F).
- Join the digits.
Example 1: a byte
10110101 splits cleanly into 1011 0101. 1011 is B (11 in decimal) and 0101 is 5. Answer: B5.
Example 2: when the length is not a multiple of four
100111100 has 9 bits. Group from the right: 1 0011 1100. Pad the lonely 1 to 0001, then look each group up: 1, 3, C. Answer: 13C.
You can sanity-check it in decimal: 100111100 is 316, and 1 x 256 + 3 x 16 + 12 = 316.
The lookup table
| Binary | Hex | Binary | Hex |
|---|---|---|---|
| 0000 | 0 | 1000 | 8 |
| 0001 | 1 | 1001 | 9 |
| 0010 | 2 | 1010 | A |
| 0011 | 3 | 1011 | B |
| 0100 | 4 | 1100 | C |
| 0101 | 5 | 1101 | D |
| 0110 | 6 | 1110 | E |
| 0111 | 7 | 1111 | F |
Two groups make a byte, so a byte is always two hex digits. 1010 1111 is AF.
Common mistakes
- Grouping from the left.
100111100grouped from the left gives the wrong answer. Always start at the last digit. - Padding the wrong side. For whole numbers, zeros go on the left.
- Reading 1011 as eleven. From
1010up, the digit is a letter.
In code
format(int('100111100', 2), 'X') # '13C' parseInt('100111100', 2).toString(16).toUpperCase() // '13C' Want to check your own numbers and see each step? Use the free binary to hex converter: https://thecodetranslator.com/binary-code-translator/binary-to-hex/
