Ruled

Number systems and computer codes

Binary, octal, decimal and hexadecimal; every conversion between them; binary arithmetic including 1's and 2's complement; and the ASCII, Unicode, BCD and EBCDIC codes.

A number system is a way of writing numbers using a fixed set of symbols. The base (or radix) is how many symbols it has, and it decides the place value of each column.

SystemBaseSymbols
Binary
Octal
Decimal
Hexadecimal, then A B C D E F for

A number is written with its base as a subscript when there is any doubt: , , .

Why a computer uses binary

An electronic circuit reliably distinguishes two states — voltage present or absent, switch on or off, charge stored or drained. Two states means two symbols, so binary. Ten states would need ten distinguishable voltage levels, and small amounts of electrical noise would make them unreliable. Everything else follows from that engineering fact.

Octal and hexadecimal exist for human convenience: they are shorthand for binary, because and , so each octal digit stands for exactly 3 bits and each hex digit for exactly 4. Writing a 32-bit address as hex digits is far easier than as ones and zeros.

Positional notation

In any base , the digit in position (counting right from ) has place value . To the right of the point, positions are

The powers of 2 worth memorising:

Converting to decimal — expand the place values

Multiply each digit by its place value and add. This works from any base.

Converting from decimal — divide, then read the remainders upward

For the integer part: divide repeatedly by the new base, keeping the remainders. The answer is the remainders read bottom to top.

For the fractional part: multiply repeatedly by the new base, keeping the integer part of each product. The answer is those integers read top to bottom. Stop when the fraction becomes or when enough places have been obtained — some fractions never terminate in binary.

The direction of reading is where marks are lost. Integer part: remainders upward. Fraction: carries downward. Two different directions in the same question.

Converting binary ↔ octal — group in threes

Because . Group the bits in threes from the binary point outwards, padding with zeros at the outer ends, and replace each group by its octal digit.

Converting binary ↔ hexadecimal — group in fours

Because . Identical method, groups of four.

The 4-bit table, worth knowing outright:

BinHexBinHex
0000010008
0001110019
001021010A
001131011B
010041100C
010151101D
011061110E
011171111F

Octal ↔ hexadecimal has no direct shortcut: go through binary.

Binary arithmetic

Addition


Subtraction

Multiplication

Identical to decimal long multiplication, but each partial product is either the multiplicand or zero, since the only digits are and .

Division

Long division, comparing and subtracting as usual.

Representing negative numbers

Three schemes, each an improvement on the last.

Signed magnitude

The leftmost bit is the sign bit: for positive, for negative. The rest is the magnitude. In 8 bits:

Simple to read, but it gives two zeros ( and ) and requires separate circuitry for subtraction.

1's complement

Invert every bit of the positive number.

Still has two representations of zero, and needs an end-around carry when adding.

2's complement — what real computers use

Take the 1's complement and add 1.

A faster equivalent method: copy bits from the right up to and including the first 1, then invert everything to the left of it.

Why hardware uses it: there is exactly one zero, and subtraction becomes addition

so a single adder circuit performs both operations, with any final carry out simply discarded.

Computer codes

Numbers are one thing; letters and symbols need a code that assigns a number to every character.

BCD — Binary Coded Decimal

Each decimal digit is coded separately in 4 bits.

Note this is not the same as the binary value of , which is . BCD wastes space (the six patterns 1010–1111 are unused) but converts to and from decimal trivially, so it is used in calculators and digital displays.

ASCII

American Standard Code for Information Interchange. 7 bits, so characters, usually stored in one byte with the top bit spare. Extended ASCII uses all 8 bits for characters.

Ranges worth remembering:

CharactersASCII (decimal)
A–Z
a–z
Space
Enter (CR)

Useful consequences: uppercase and lowercase differ by exactly , so case conversion is one addition; and the digit characters are higher than the values they represent, so subtracting from the code of '7' gives the number .

EBCDIC

Extended Binary Coded Decimal Interchange Code. An 8-bit code ( characters) developed by IBM for its mainframes. Not compatible with ASCII.

Unicode

ASCII covers only English. Unicode assigns a unique code point to every character of every writing system — Latin, Devanagari, Malayalam, Arabic, Chinese, mathematical symbols and emoji — over a million possible. UTF-8 is the usual encoding: it uses 1 byte for ASCII characters (so it is backward compatible) and 2 to 4 bytes for others. Unicode is why a single web page can show English and Malayalam together.

Worked examples

4 solved

Every step is shown, in the order you would write it in an answer book.

Example 1

Converting a binary number with a fraction to decimal

Question

Convert to decimal.

  1. Write the place value above each digit

  2. Expand the integer part

  3. Expand the fractional part

  4. Add

Answer

Example 2

Converting a decimal number with a fraction to binary

Question

Convert to binary.

  1. Integer part — divide by 2 repeatedly, recording remainders

    Read the remainders bottom to top: .

    Check:

  2. Fractional part — multiply by 2 repeatedly, recording carries

    Read the bold integer parts top to bottom: .

    Check:

  3. Combine the two parts

Answer

NoteRemainders are read upward, carries downward. Writing both checks costs a few seconds and guarantees the marks.

Example 3

Converting between octal and hexadecimal

Question

Convert to hexadecimal.

  1. There is no direct route — go through binary

    Octal and hexadecimal have no simple digit correspondence, because is not a power of . Binary is the bridge: bits per octal digit, bits per hex digit.

  2. Expand each octal digit into 3 bits

  3. Regroup the same bits into fours, from the right

    A leading zero is added at the left to complete the first group of four.

  4. Replace each group of four with its hex digit

  5. Verify through decimal


Answer

Example 4

Subtraction using 2's complement

Question

Using 8-bit 2's complement arithmetic, evaluate .

  1. Write both numbers in 8-bit binary


  2. Find the 2's complement of the number being subtracted

    Invert every bit of :

    Add :

    So is represented by .

  3. Add, instead of subtracting

  4. Discard the carry out of the leftmost column

    A carry out of the most significant bit is simply thrown away in 2's complement addition. The result is

    The leading bit is , so the answer is positive.

  5. Convert back to decimal

    And indeed

  6. Note what this buys the hardware

    No subtractor circuit was used anywhere. The machine inverted, added one, and then added — which is why a CPU needs only an adder and an inverter to do both addition and subtraction.

Answer

NoteIf the leading bit of the result is 1, the answer is negative — take its 2's complement to read the magnitude.

Practice problems

7 with solutions

Work each one on paper first. The full solution — not just the answer — is one click away.

Problem 1Basic

Convert to decimal: (a) (b) (c)

Show solution

(a)

(b)

(c) — with A and F

Answer(a) (b) (c)
Problem 2Basic

Convert to (a) binary (b) octal (c) hexadecimal.

Show solution

(a) Binary — divide by :

Reading upward: . Check:

(b) Octal — group the binary in threes from the right:

Check:

(c) Hexadecimal — group the same bits in fours from the right:

Check:

Converting once to binary and then regrouping is far quicker than dividing three separate times.

Answer(a) (b) (c)
Problem 3Exam level

Convert to binary, and to octal and hexadecimal.

Show solution

Part 1 — to binary. Multiply by repeatedly:

Reading the integer parts downward: .

Check:

Part 2 — to octal. Group in threes outward from the binary point:

Part 3 — the same number to hexadecimal. Group in fours outward from the point, padding at both outer ends:

Note the padding directions: to the left of the point pad on the far left; to the right of the point pad on the far right. Padding the fraction on the wrong side changes its value.

Check: ; ✓;

Answer;  
Problem 4Exam level

Perform in binary: (a) (b) (c)

Show solution

(a) Addition

Column by column from the right: (write , carry ); (write , carry ); (write , carry ); (write , carry ); the final carry is written down.

Result: . Check:

(b) Subtraction

From the right: needs a borrow, giving ; the next column, now reduced, gives ; then ; then ; then .

Result: . Check:

(c) Multiplication

Each partial product is either or a copy of , shifted left one place each time.

Result: . Check:

Answer(a) (b) (c)
Problem 5Exam level

Find the 1's and 2's complement of , and explain why computers use 2's complement rather than signed magnitude.

Show solution

1's complement — invert every bit:

2's complement — add to the 1's complement:

Shortcut check. Copy bits from the right up to and including the first , then invert the rest. The original ends in ; keeping the final and inverting everything left of it gives

Why 2's complement is preferred. Three reasons.

1. One zero, not two. In signed magnitude, is and is — two bit patterns for the same value. Comparisons must then test for both, and one of the available patterns is wasted. In 2's complement there is exactly one zero, and the 8-bit range is the clean to .

2. Subtraction becomes addition. In 2's complement,

so no subtractor circuit is needed at all — an inverter and the existing adder suffice. In signed magnitude the hardware must compare magnitudes, decide which is larger, subtract the smaller from the larger, and then work out the sign of the answer separately. That is far more circuitry for the same job.

3. Carries need no special handling. Any carry out of the most significant bit is simply discarded and the answer is still correct. The 1's complement scheme instead requires an end-around carry — the carry out must be added back into the least significant bit — which is an extra step and an extra piece of hardware.

Simpler circuitry that is also faster is why every general-purpose processor represents signed integers in 2's complement.

Answer1's complement ; 2's complement . 2's complement is used because it has a single zero, turns subtraction into addition, and needs no end-around carry.
Problem 6Exam level

What is ASCII? Given that 'A' is and 'a' is , find the codes for 'E' and 'e', and explain how a program converts a letter to uppercase.

Show solution

ASCIIAmerican Standard Code for Information Interchange — is a character encoding that assigns a unique number to every letter, digit, punctuation mark and control character. It uses 7 bits, so it defines characters, normally stored one per byte. Extended ASCII uses the eighth bit as well, for characters.

Codes for 'E' and 'e'. The letters are consecutive, so 'E' is the 5th letter:

The relationship between cases.

Every lowercase letter is exactly more than its uppercase counterpart, and this holds for the whole alphabet because both runs are contiguous and in the same order.

Converting case. A program therefore does arithmetic, not a table lookup:

Since , the difference is a single bit — bit 5. So the conversion is really one bit operation: clear bit 5 for uppercase, set it for lowercase.

A caution. The program must first check that the character actually is a letter. Blindly subtracting from a digit or a punctuation mark produces a different, wrong character — subtracting from '5' () gives , a control character.

Other useful ASCII facts. Digits '0' to '9' occupy , so the numeric value of a digit character is its code minus ; space is ; and carriage return is .

AnswerASCII is a 7-bit, 128-character encoding. 'E' , 'e' . Lowercase is always (i.e. bit 5) above uppercase, so case conversion is one subtraction or addition — applied only after checking the character is a letter.
Problem 7Challenge

Distinguish between BCD and pure binary representation of a decimal number, and explain where BCD is preferred despite being less efficient.

Show solution

Pure binary treats the number as a single quantity and converts the whole of it. BCD codes each decimal digit separately in 4 bits.

Take .

Pure binary:

BCD:

The two bit patterns are completely different, and BCD needed two more bits for the same number.

Why BCD is less efficient. Four bits can represent patterns, but a decimal digit needs only . The six patterns to are invalid in BCD and simply wasted. The waste grows with the size of the number: representing a 10-digit value takes 40 bits in BCD but only 34 in pure binary. BCD arithmetic is also more complicated, because after adding two BCD digits the hardware must check whether the result exceeded and, if so, add to correct it.

Where BCD is preferred anyway. Whenever the number spends most of its life being displayed or entered as decimal, and comparatively little of it being calculated with.

  1. Digital displays, calculators and instruments. Each 4-bit group drives one digit of a seven-segment display directly. In pure binary, showing on a display would first require dividing by to extract each digit — a division per digit, per refresh.

  2. Exact decimal fractions in financial work. Values such as have no terminating representation in binary, so repeated pure-binary arithmetic on money accumulates rounding error. BCD (and the decimal types built on it) keeps decimal fractions exact, which is why currency is often held in decimal rather than binary floating point.

  3. Frequent conversion at the boundary. If a value is read from a keypad and written to a display many times but added only rarely, the cost of conversion dominates the cost of arithmetic — and BCD makes conversion nearly free.

The general principle. Pure binary optimises storage and calculation; BCD optimises conversion to and from decimal, and decimal exactness. Which is more efficient depends entirely on which of those the application does more of.

AnswerPure binary converts the whole number (); BCD codes each digit in 4 bits (), wasting the six patterns above . BCD is preferred where numbers are mainly displayed or entered in decimal, or where decimal fractions must stay exact — calculators, instrument displays and financial arithmetic.