☰ Year plan · Communication Technology

Hexadecimal and binary together

Week 5 · Unit 1 Number systems (5): more decimal to hexadecimal, hexadecimal to binary and binary to hexadecimal · 3 lessons
3

Binary to hexadecimal: grouping bits in fours

ICT Secondary 3 Term 1, Unit 1, Topic 1: pp. 22–26
GoalConvert binary to hexadecimal by grouping the bits in fours from the right.
New words
grouping · splitting the bits into groups of fourpadding · adding zeros on the left of the first group so that it has four bitsbyte as two symbols · 8 bits are two groups of four, so a byte is always two hexadecimal symbols
Explanation

To convert binary to hexadecimal, split the bits into groups of four, starting from the right. If the group at the left end has fewer than four bits, add zeros on its left. Then replace every group by its hexadecimal symbol from the lookup table. For example 11010111 splits into 1101 and 0111, which are D and 7, so (11010111)₂ = (D7)₁₆. And 101110 splits from the right into 10 and 1110; the group 10 is padded to 0010, so the answer is (2E)₁₆. Always start from the right, because the right end holds the place worth 1. A byte has 8 bits, so it is always two hexadecimal symbols, from 00 to FF.

StepResult
Bits101110
Groups from the right10 | 1110
Pad the left group0010 | 1110
Symbols2 | E
Worked examples
Groups11010111
SymbolsD7
Convert 11010111. Two groups of four are 1101 = D and 0111 = 7, so the answer is D7. Check: D7 is 13×16 + 7 = 215, and the bits are 128 + 64 + 16 + 4 + 2 + 1 = 215.
GroupingGroupsAnswerValue
from the right0101 | 10115B91
from the left1011 | 0110B6182
Grouping from the wrong end gives a wrong answer. The bits 1011011 split from the right as 101 and 1011, padded to 0101 and 1011, which is 5B and equals 91. Splitting from the left as 1011 and 011, padded to 1011 and 0110, gives B6, which is 182, twice as much.
Php
1<?php
2echo strtoupper(dechex(bindec("11010111"))), "\n";
3echo decbin(hexdec("3B"));
Output
D7
111011
PHP has no direct function from binary to hexadecimal. This program goes through a decimal number: bindec reads the bits, dechex writes hexadecimal in lower case, and strtoupper makes capitals. Then hexdec and decbin go the other way.
Class activity

Take a byte of your own, eight bits. Convert it to hexadecimal by grouping, then to decimal with the binary place values, and to decimal again from the hexadecimal. The two decimal answers must be equal.

Practice
1
Convert 10011100 to hexadecimal.
2
Convert 111001 to hexadecimal.
3
Convert 1101011 to hexadecimal.
4
How many hexadecimal symbols are needed for a pattern of 16 bits?
5
Why is the grouping started from the right?