الأسبوع 5 · الوحدة ١ «النظم العددية» (٥): مثال آخر على التحويل إلى السداسي عشر، ومن السداسي عشر إلى الثنائي ومن الثنائي إلى السداسي عشر · 3 دروس
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.
Step
Result
Bits
101110
Groups from the right
10 | 1110
Pad the left group
0010 | 1110
Symbols
2 | E
Worked examples
Groups
1101
0111
Symbols
D
7
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.
Grouping
Groups
Answer
Value
from the right
0101 | 1011
5B
91
from the left
1011 | 0110
B6
182
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 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.
1001 = 9 and 1100 = C, so 9C.
2
Convert 111001 to hexadecimal.
From the right: 11 and 1001, padded to 0011 and 1001, so 39.
3
Convert 1101011 to hexadecimal.
From the right: 110 and 1011, padded to 0110 and 1011, so 6B.
4
How many hexadecimal symbols are needed for a pattern of 16 bits?
16 ÷ 4 = 4 symbols.
5
Why is the grouping started from the right?
The right end holds the place worth 1, so the groups line up with the hexadecimal places 1, 16, 256 …