Microprocessors · Lecture Notes
Chapter 1.2: Number Systems
Everything inside a microprocessor is made of bits: registers, memory cells, the lines of the address and data buses, flags. The pattern 1111 1011 sitting in a register can, depending on context, be 251, be −5, be part of a character, or be the exponent field of a floating-point number. The pattern itself carries no meaning; the meaning comes from the representation the programmer chooses. This chapter collects the number representations needed before moving on to 8086 programming. It starts with positional number systems and converts between bases both by hand and with 8086 instructions. It then examines the two’s complement representation of negative numbers, binary and hexadecimal arithmetic, and the difference between carry and signed overflow. The last sections cover the hardware counterpart of the bit (voltage levels, flip-flops), the IEEE 754 floating-point format, BCD, byte order, and the Gray code.
Learning outcomes
- Read positional systems
- Compute the value of a decimal, binary, or hexadecimal number from its digit weights; state the ranges of the units bit, nibble, byte, and word; use the assembly suffixes
b,h, andocorrectly. - Convert between bases
- Convert a decimal integer with the divide-and-remainder method and the fractional part with repeated multiplication by 2; move between binary and hexadecimal by grouping bits in fours; trace programs that do the same job with the
DIVandSHRinstructions. - Use signed numbers
- Write negative numbers in two’s complement; compare it with one’s complement and sign-magnitude; explain the 8-bit and 16-bit signed ranges, sign extension, and fixed-point fractions.
- Do arithmetic and interpret flags
- Add and subtract in binary and hexadecimal; turn subtraction into addition of a complement; find, with justification, the values of the CF and OF flags after an operation.
- Decode encodings
- Decode and encode a 32-bit IEEE 754 pattern; do BCD addition with the correction step; write the little-endian memory layout of a multibyte value; produce a Gray code and convert it back.
- Connect bits to hardware
- Explain how voltage levels correspond to bits, how the types of flip-flops behave, and how a register is built from D flip-flops.
1.2.1Representing numbers
A number is an abstract concept. Five apples, five fingers, and five days share the same quantity; but to write that quantity on paper, on stone, or in a circuit, a representation is needed. The choice of representation determines how easy it will be to do things with numbers. This section uses two old representations to explain why positional systems took the form they have today.
1.2.1.1From tally sticks to symbols
People first counted with concrete objects: pebbles, knots, sticks. Someone counting with sticks shows five as | | | | |. This representation has one advantage: the value equals the number of symbols, and it can be read without knowing any rules. Its drawback is just as clear. A hundred takes a hundred strokes. To compare two numbers you have to count the strokes one by one.
In the Roman Empire a partial solution to this problem was found. Small numbers were still written with strokes (III is three), but separate symbols were used for certain groups: V stood for five sticks and X for ten. The representation we use today rests on a completely different idea: the value of a digit depends not only on the digit itself but also on its position in the number. The 7 in 754 is not seven but seven hundred. Figure 1.2.1 puts the three representations side by side.
1.2.1.2Roman numerals
The Roman system has seven symbols. Table 1.2.1 lists them with their values. A number is read by adding the values of the symbols and, where needed, subtracting.
| Symbol | I | V | X | L | C | D | M |
|---|---|---|---|---|---|---|---|
| Value | 1 | 5 | 10 | 50 | 100 | 500 | 1000 |
Roman numerals are read with an addition and subtraction rule. A small symbol after a larger one is added: VI = 5 + 1 = 6. A small symbol before a larger one is subtracted: IV = 5 − 1 = 4. Subtraction is used in only six pairs: IV (4), IX (9), XL (40), XC (90), CD (400), and CM (900).
The safe way to read is to split the number from left to right into groups of value. Each group is either symbols that are simply added or one of the six subtraction pairs. The values of the groups are found and added.
Let us read MCMLXXXVI. From left to right the groups are M, CM, LXXX, and VI. M = 1000. CM is a subtraction pair: because C comes before M it gives 1000 − 100 = 900. LXXX = 50 + 10 + 10 + 10 = 80. VI = 5 + 1 = 6. The total is 1000 + 900 + 80 + 6 = 1986.
For MMVII the groups are M, M, and VII: 1000 + 1000 + 7 = 2007. MMVI, written with one I fewer, is 2006.
The Roman system has two shortcomings, and both make arithmetic hard. The first is that there is no symbol for zero. The second is that there is no notion of place value: X is ten everywhere. So it is impossible to write two Roman numerals one under the other and add them column by column. To add MCMLXXXVI and MMVII you first have to convert both to their values. Multiplication and division are even more laborious. The positional system removes both shortcomings at once.
Applying the subtraction rule to every small-large pair. IC is not 99; 99 is written XCIX (90 + 9). When reading MCMXLIV, it is also common to read XL like LX (60): in XL the X comes before the L, so it is subtracted and the group is 40. The correct reading is 1000 + 900 + 40 + 4 = 1944.
1.2.2Positional number systems
In a positional system every digit position has a weight, and the digit is multiplied by this weight. The weights are powers of the base. In the decimal system the weights go 1, 10, 100, 1000; in binary, 1, 2, 4, 8. This section treats the three bases (10, 2, 16) with the same formula, defines the data units of the computer world, and shows how numbers are written in assembly.
1.2.2.1The decimal system and the general formula
The system we use in daily life is the decimal system. Its base is 10 and it has ten digits: 0, 1, 2, …, 9. In the number 754 the 4 is in the ones place, the 5 in the tens place, and the 7 in the hundreds place. The value is the sum of each digit multiplied by its own place weight: 7 × 100 + 5 × 10 + 4 × 1 = 754. Figure 1.2.3 shows this sum place by place.
A positional number system is a system in which the value of a digit is determined by the position it occupies. The value of an n-digit number dn−1 … d1 d0 written in base (radix) b is
N = dn−1 × bn−1 + … + d1 × b1 + d0 × b0 = Σi=0..n−1 di × bi
Here each digit di lies between 0 and b − 1; i is the position of the digit and is counted from the right starting at 0.
The formula is the same for every base; only b changes. So there is no need to learn a new rule for binary and hexadecimal numbers. The set of digits changes with the base: base 10 has ten digits, base 2 has two, and base 16 has sixteen. A digit can never be equal to or greater than the base. There is no digit 2 in a binary number, and no single digit “10” in a decimal one.
1.2.2.2The importance of position, and zero
754 and 547 consist of the same three digits, but their values are very different. The 7 has the value 700 when put on the far left and the value 7 when put on the far right. Figure 1.2.4 shows the two numbers side by side. Where X is ten everywhere in the Roman system, in the positional system the same digit takes the value 700, 70, or 7 depending on its position.
The rightmost position is the “ones” place in every base. The reason is that the zeroth power of every nonzero number is 1: x0 = 1. In mathematics 00 is considered indeterminate; in number systems and polynomials it is taken as 1 by convention. Since the base is never 0, this detail causes no problem in practice.
The digit zero is essential for a positional system to work. In the number 705 the tens place is empty. If this gap is not filled with a zero, 705 and 75 cannot be told apart. Here zero is a placeholder meaning “nothing here.” The Roman system did not need a zero, because the value of its symbols was independent of position.
1.2.2.3The binary system
The reason computers use binary instead of decimal is electronics. Keeping a circuit element at one of ten different voltage levels and telling these levels apart reliably in the presence of noise is hard. An element with two states is easy to build. A transistor is either conducting or cut off. A line is either at high voltage or low. A capacitor is either charged or empty. These two states are named 1 and 0. Figure 1.2.5 shows how the voltage on a line carries the values 1 and 0 over time.
The binary system is the positional system with base 2. Its digits are only 0 and 1. The place weights are powers of 2: 20 = 1, 21 = 2, 22 = 4, 23 = 8, 24 = 16, 25 = 32, 26 = 64, 27 = 128, … Each digit of a binary number is called a bit (binary digit).
The binary system uses many more digits than decimal. The number 1000 is four digits in decimal and takes ten in binary. In return, because each digit has only two values, the rules of arithmetic are very simple. The addition table has four rows and the multiplication table also has four. This simplicity makes it possible to build an adder circuit from a few logic gates.
1.2.2.4Bit, nibble, byte, and word
Bits are processed not one at a time but in groups of fixed width. Each group width has a name. Figure 1.2.6 splits a 32-bit value into these groups; Table 1.2.2 gives the range of each unit and its counterpart on the 8086.
| Unit | Bits | Unsigned range | On the 8086 |
|---|---|---|---|
| bit | 1 | 0 … 1 | a flag (CF, ZF …) |
| nibble | 4 | 0 … 15 (0h … Fh) | one hexadecimal digit, one BCD digit |
| byte | 8 | 0 … 255 | AL, AH, BL …; DB |
| word | 16 | 0 … 65,535 | AX, BX, CX, DX …; DW |
| double word | 32 | 0 … 4,294,967,295 | the DX:AX pair; DD |
The third column of the table follows from a single rule: with n bits, 2n different patterns can be written. Counted from 0, the largest value is 2n − 1. For 8 bits there are 28 = 256 patterns and the largest value is 255. For 16 bits there are 65,536 patterns and the largest value is 65,535. These limits come up constantly in 8086 programming. You cannot store 256 in a byte; you cannot store 70,000 in a word.
A nibble is a group of 4 bits. A byte is a group of 8 bits and the smallest addressable unit of memory. A word is a group of 16 bits on the 8086, and a double word is a group of 32 bits. The leftmost bit of a group is called the most significant bit (MSB), and the rightmost bit the least significant bit (LSB).
The word width depends on the processor. The 8086 is a 16-bit processor: its general-purpose registers are 16 bits and its data bus carries 16 bits in one bus cycle. The AX register consists of two bytes. The high byte is AH and the low byte is AL. If AX = 1234h, then AH = 12h and AL = 34h. A 32-bit value does not fit in a single register on the 8086; the multiply and divide instructions hold such values in the DX:AX pair. In this pair DX carries the high word and AX the low word.
1.2.2.5Reading binary numbers
In assembly source code, binary numbers end with the letter b: 101b is five. To find the value of a binary number the positional formula is applied. Since the digits are only 0 and 1, no multiplication is needed. Positions that hold 0 add nothing to the sum, and positions that hold 1 add their weights. The shortcut is this: add up only the weights of the positions that hold 1.
Knowing the 8-bit weights by heart speeds up reading: from left to right 128, 64, 32, 16, 8, 4, 2, 1. Figure 1.2.7 works out the example 10100101b: 128 + 32 + 4 + 1 = 165. In a number with fewer than 8 digits the weights still start from the right. The missing digits on the left are taken as 0.
Let us convert 1111011b to decimal. The number has seven digits; the weights go from 2⁰ to 2⁶ starting at the right. Let us add the digits one by one from right to left and follow the running total:
- Digit 0: 1 × 2⁰ = 1, running total 1.
- Digit 1: 1 × 2¹ = 2, running total 3.
- Digit 2: 0 × 2² = 0, running total 3.
- Digit 3: 1 × 2³ = 8, running total 11.
- Digit 4: 1 × 2⁴ = 16, running total 27.
- Digit 5: 1 × 2⁵ = 32, running total 59.
- Digit 6: 1 × 2⁶ = 64, running total 123.
The result is (1111011)2 = 1 + 2 + 0 + 8 + 16 + 32 + 64 = 123. By the shortcut: if all seven bits were 1 the value would be 127; since the 2² position is 0, 127 − 4 = 123.
The trick in the last sentence of the example is a general rule. The number whose n bits are all 1 is 2n − 1. The value of a number with a few 0 bits can be found by subtracting the weights of the 0 bits from this upper bound. For numbers that are mostly 1s this route is faster.
1.2.2.6The hexadecimal system
Binary numbers are long and tiring to read. Writing a 16-bit address as a string of 0s and 1s takes space and makes mistakes easy. The decimal system gives a short notation, but converting between decimal and binary needs division and multiplication. The hexadecimal system combines two advantages: it is short, and converting it to binary needs no computation.
The hexadecimal system is the positional system with base 16. It has sixteen digits: 0–9, and the letters A, B, C, D, E, F for the values 10–15. The place weights are powers of 16: 1, 16, 256, 4096, 65,536, …
Because 16 = 24, each hexadecimal digit corresponds to exactly four bits, that is, one nibble. Table 1.2.3 gives the decimal and hexadecimal counterparts of the sixteen nibbles. This is the only table that must be known by heart when working with number systems. A byte is written with two hexadecimal digits and a word with four: 1010 0101b = A5h.
| Decimal | Binary | Hexadecimal | Decimal | Binary | Hexadecimal |
|---|---|---|---|---|---|
| 0 | 0000 | 0 | 8 | 1000 | 8 |
| 1 | 0001 | 1 | 9 | 1001 | 9 |
| 2 | 0010 | 2 | 10 | 1010 | A |
| 3 | 0011 | 3 | 11 | 1011 | B |
| 4 | 0100 | 4 | 12 | 1100 | C |
| 5 | 0101 | 5 | 13 | 1101 | D |
| 6 | 0110 | 6 | 14 | 1110 | E |
| 7 | 0111 | 7 | 15 | 1111 | F |
In assembly, hexadecimal numbers end with the letter h: 5Fh = 5 × 16 + 15 = 95. A 0 is put in front of hexadecimal numbers that start with a letter: 0E120h. This zero does not change the value of the number, but it tells the assembler that it is a number. Without the zero the assembler takes E120h for the name of a variable or a label. Table 1.2.4 summarizes the consequences of this rule.
| Notation | Meaning |
|---|---|
MOV AL, 0FFh | AL = 255; correct notation |
MOV AL, FFh | error: FFh is read as an undefined name |
MOV AX, 10 | decimal 10 (= 0Ah); without a suffix the number is decimal |
The decimal value of a hexadecimal number is again found with the positional formula. For 1234h the weights are 4096, 256, 16, and 1: 1 × 4096 + 2 × 256 + 3 × 16 + 4 × 1 = 4096 + 512 + 48 + 4 = 4660. Figure 1.2.9 shows this calculation. Digits that are letters are first converted to their decimal values and then multiplied.
Let us convert A12Fh to decimal. First the letters are decoded: A = 10, F = 15. The weights are 16⁰ = 1, 16¹ = 16, 16² = 256, and 16³ = 4096. Starting from the right:
- F × 16⁰ = 15 × 1 = 15; running total 15.
- 2 × 16¹ = 32; running total 47.
- 1 × 16² = 256; running total 303.
- A × 16³ = 10 × 4096 = 40,960; running total 41,263.
The result is (A12F)16 = 41,263. Since the value is less than 65,535, it fits in a 16-bit register: MOV AX, 0A12Fh is a valid instruction.
1.2.2.7Grouping in fours between binary and hexadecimal
Because each hexadecimal digit corresponds to four bits, converting between binary and hexadecimal is as easy as looking a word up in a dictionary. The binary number is split into groups of four starting from the right. If the leftmost group is shorter than four bits, 0s are added on its left. Each group is converted to a single hexadecimal digit using Table 1.2.3.
Let us convert 1010 1011 0101 1100b to hexadecimal. The number is already split into groups of four. 1010 = 8 + 2 = 10, that is, A. 1011 = 8 + 2 + 1 = 11, that is, B. 0101 = 4 + 1 = 5. 1100 = 8 + 4 = 12, that is, C. The result is AB5Ch. Because it starts with A, it is written 0AB5Ch in assembly.
The reverse direction uses the same table: each hexadecimal digit is expanded to four bits. 3Eh → 0011 1110b. An example whose bit count is not a multiple of four: 1101011b is seven bits. Split from the right, the groups are 110 and 1011. A 0 is added to the left group: 0110 1011 → 6Bh.
This is why programmers write binary data in hexadecimal almost always. A byte is exactly two hexadecimal digits, a word exactly four. 8086 debuggers and emulators show register and memory contents in hexadecimal. When a register’s value is read in hexadecimal, which bits are 1 is visible at a glance. For example, if AL = 80h only bit 7 is one; if AL = 0Fh the four bits of the low nibble are one.
The same method works for the octal system. Because 8 = 23, each octal digit corresponds to three bits and the binary number is split into groups of three. 0100 0001b is written with groups of three as 001 000 001; this is 101o. The octal system was common on old computers; it is rarely used in 8086 programming.
Splitting the groups of four starting from the left. If 1101011b is split from the left, the groups 1101 and 011 come out; if a 0 is added to the right group on its right, 1101 0110 = D6h is found. This is wrong: a zero added on the right doubles the number. Groups always start from the right, that is, from the ones place; missing bits are added only on the left.
1.2.2.8Number notations in assembly
The emu8086 assembler accepts constants in four bases and as characters. The base is determined by the ending at the end of the number, that is, the suffix. Table 1.2.5 lists five different notations that load 65 into AL, and one negative constant.
| Notation | Base | Value going to AL |
|---|---|---|
MOV AL, 65 | decimal (no suffix or d) | 65 = 41h |
MOV AL, 41h | hexadecimal | 65 = 41h |
MOV AL, 01000001b | binary | 65 = 41h |
MOV AL, 101o | octal (o or q) | 65 = 41h |
MOV AL, 'A' | ASCII character | 65 = 41h |
MOV AL, -1 | decimal, signed | FFh |
The first five rows all produce the same machine code: B0 41. Here B0h is the opcode of the instruction “load a constant byte into AL”; 41h is the constant itself. The assembler converts the number in the source code to binary whatever base it finds it in, and embeds it in the instruction. The processor never sees the source code; it sees only the bits 1011 0000 0100 0001. The base is only a writing convenience for people.
The last row is interesting too: MOV AL, -1 loads FFh into AL. The assembler converts the negative constant to two’s complement form: for −1, 256 − 1 = 255 = FFh. The bit pattern FFh that goes into AL is the same pattern MOV AL, 255 loads. To the processor there is no difference between the two.
Forgetting the suffix. MOV AL, 41 loads decimal 41, that is 29h, into AL, not 41h. If the h suffix is left off when a hexadecimal value is copied from a memory dump or a table, the program runs with the wrong value and gives no error. The assembler cannot notice this, because 41 is a valid decimal number.
1.2.3Base conversions
Converting a number from another base to decimal is done with the positional formula: the digits are multiplied by their weights and added. The reverse direction, from decimal to another base, needs a separate method. This section presents the divide-and-remainder method for the integer part and the multiplication method for the fractional part. It shows why both methods work and traces two small 8086 programs that do the same job, step by step.
1.2.3.1The divide-and-remainder method
The divide-and-remainder method converts a decimal integer to base b. The number is divided by b; the quotient is kept and the remainder is written down as a digit. Division continues on the quotient until it becomes 0. Reading the remainders from last to first (bottom to top) gives the representation of the number in base b: the first remainder is the lowest digit.
Why the method works can be seen from the positional formula. Write N = dkbk + … + d1b + d0. Every term except d0 is a multiple of b. So when N is divided by b, the remainder is exactly d0 and the quotient is dkbk−1 + … + d1. The quotient is the number with its rightmost digit deleted. Dividing it by b again gives d1. Each division produces one digit and shortens the number by one digit. Because the remainder is always between 0 and b − 1, every remainder is a valid digit.
In the decimal system the same method is known without being named. Dividing 754 by 10 gives quotient 75 and remainder 4; the remainder is the last digit. Dividing 75 by 10 gives remainder 5 and quotient 7. The method is just this familiar operation done in another base.
Let us convert 39 to hexadecimal. 39 ÷ 16 = 2, remainder 7; 7 is the ones digit. 2 ÷ 16 = 0, remainder 2. The quotient is 0, so we stop. Reading the remainders from bottom to top: 27h. Check: 2 × 16 + 7 = 39.
A larger number: let us convert 43,868 to hexadecimal.
- 43,868 ÷ 16 = 2741, remainder 12 → C.
- 2741 ÷ 16 = 171, remainder 5.
- 171 ÷ 16 = 10, remainder 11 → B.
- 10 ÷ 16 = 0, remainder 10 → A. Quotient 0: stop.
Reading the remainders from bottom to top gives AB5Ch. Because it starts with A, it is written 0AB5Ch in assembly. Check: 10 × 4096 + 11 × 256 + 5 × 16 + 12 = 40,960 + 2816 + 80 + 12 = 43,868. This is the same number as 1010 1011 0101 1100b in the grouping example.
To compute the remainder at each division step, subtract the product of quotient and divisor from the number: 43,868 − 2741 × 16 = 43,868 − 43,856 = 12. When working with a calculator, the decimal result can be used too. 43,868 / 16 gives 2741.75. The integer part is the quotient; the fractional part, multiplied by 16, gives the remainder: 0.75 × 16 = 12.
1.2.3.2Code trace: hexadecimal digits with DIV
The divide-and-remainder method is a loop, and it turns directly into 8086 code. The 8086 DIV instruction gives the quotient and the remainder in one instruction. The following program repeatedly divides 2989 by 16 and writes the remainders into an array named rem.
ORG 100h
MOV AX, 2989 ; number
MOV BX, 16 ; base
MOV SI, 0 ; counter
again: MOV DX, 0 ; DX:AX
DIV BX ; quot, rem
MOV rem[SI], DL
INC SI
CMP AX, 0 ; quotient 0?
JNE again
RET
rem DB 4 DUP(0)Here is what the program does, line by line. ORG 100h is not an instruction but a directive given to the assembler. It declares that the program, as a .COM file, will start at offset 100h of the segment. MOV AX, 2989 puts the number to be divided into AX; in hexadecimal 2989 is 0BADh. MOV BX, 16 puts the divisor, that is, the target base, into BX. Had 2 or 8 been written into BX, the same code would have produced binary or octal digits. MOV SI, 0 clears the index that holds the position of the next remainder in the array.
The line labeled again is the top of the loop and clears DX. The reason is how DIV works. DIV BX, whose operand is a 16-bit register, divides the 32-bit DX:AX pair by BX. It writes the quotient to AX and the remainder to DX. If DX holds a leftover value from the previous pass, the dividend becomes 65,536 × DX + AX and the result comes out completely wrong. If the quotient does not fit in 16 bits, the processor also raises a divide-error interrupt. This is why DX = 0 is set before every division.
MOV rem[SI], DL writes the low byte of the remainder into element SI of the array. Because the remainder is less than 16, it fits in DL and DH is always 0. INC SI increments the index. CMP AX, 0 subtracts 0 from AX, stores the result nowhere, but sets the flags: if the quotient is 0, ZF = 1, otherwise ZF = 0. JNE again (“jump if not equal”) returns to the top of the loop while ZF = 0. When the quotient becomes 0 the jump is not taken and RET ends the program. The last line defines the four-byte array rem, initially zero.
Table 1.2.6 gives the state of the program after each important step. Register values are written in hexadecimal.
| Step | AX | DX | SI | rem (+0 … +3) | Note |
|---|---|---|---|---|---|
| first three MOVs | 0BADh | 0000h | 0 | 00 00 00 00 | BX = 0010h |
| pass 1: DIV BX | 00BAh | 000Dh | 0 | 00 00 00 00 | 2989 ÷ 16 = 186, remainder 13 (D) |
| MOV, INC, CMP | 00BAh | 000Dh | 1 | 0D 00 00 00 | AX ≠ 0 → ZF = 0, JNE jumps |
| pass 2: DIV BX | 000Bh | 000Ah | 1 | 0D 00 00 00 | 186 ÷ 16 = 11, remainder 10 (A) |
| MOV, INC, CMP | 000Bh | 000Ah | 2 | 0D 0A 00 00 | AX ≠ 0 → JNE jumps |
| pass 3: DIV BX | 0000h | 000Bh | 2 | 0D 0A 00 00 | 11 ÷ 16 = 0, remainder 11 (B) |
| MOV, INC, CMP | 0000h | 000Bh | 3 | 0D 0A 0B 00 | AX = 0 → ZF = 1, JNE falls through |
| RET | 0000h | 000Bh | 3 | 0D 0A 0B 00 | three digits found |
The loop runs three times, because 2989 has three digits in hexadecimal. The final value of SI gives the number of digits. In memory the remainders sit in the order 0D 0A 0B, starting from the lowest digit. Read from last to first they give B, A, D, that is, 0BADh. Check: 11 × 256 + 10 × 16 + 13 = 2816 + 160 + 13 = 2989. Figure 1.2.15 shows the final state.
rem array after the loop ends. The remainders of the three divisions are D, A, and B; read from last to first they give 0BADh.The array in the program is four bytes. A 16-bit number has at most four digits in hexadecimal (FFFFh), so four bytes are always enough. With base 2, 16 digits would be needed and the array would have to be defined as 16 DUP(0). To print the remainders on the screen, each must be converted to an ASCII character: add 30h for 0–9 and 37h for A–F (0Dh + 37h = 44h = 'D').
A note on the speed of the program is in order. On the 8086 a 16-bit DIV is one of the slowest instructions; with a register operand it takes about 144–162 clock cycles. In the same time dozens of MOV or ADD instructions could run. When the divisor is a power of 2 there is no need for division at all: the shift instructions do the same job much faster. Division by 2 is the most common example.
1.2.3.3Dividing by the binary base
The divide-and-remainder method works in every base. For base 2 the divisor is 2 and the remainder is always 0 or 1. The remainder of odd numbers is 1 and that of even numbers is 0.
Let us convert 45 to binary.
- 45 ÷ 2 = 22, remainder 1.
- 22 ÷ 2 = 11, remainder 0.
- 11 ÷ 2 = 5, remainder 1.
- 5 ÷ 2 = 2, remainder 1.
- 2 ÷ 2 = 1, remainder 0.
- 1 ÷ 2 = 0, remainder 1. Quotient 0: stop.
Reading the remainders from bottom to top gives 101101b. Check: 32 + 8 + 4 + 1 = 45. In an 8-bit register this number sits as 0010 1101b = 2Dh.
For large numbers division by 2 takes long: a number like 43,868 needs sixteen steps. A faster way is to convert the number to hexadecimal first and then expand each digit into four bits. Since 45 ÷ 16 = 2, remainder 13 (D), 45 = 2Dh. Expanding 2 = 0010 and D = 1101 gives 0010 1101b. This route ends with two divisions and a table lookup.
1.2.3.4Code trace: the remainders come from CF
Shifting a binary number right by one bit divides it by 2. Just as deleting the last digit of a decimal number divides it by 10, dropping the last bit of a binary number divides it by 2. The bit that falls out is the remainder of the division. The 8086 SHR (shift right, logical) instruction writes this dropped bit into the carry flag (CF). The following program uses this observation: without DIV, it drops the binary digits of 45 one by one into CF and collects them in BL.
ORG 100h
MOV AL, 45 ; dividend
MOV CX, 8 ; 8 bits
bit: SHR AL, 1 ; rem → CF
RCR BL, 1 ; CF → BL
LOOP bit
RETMOV AL, 45 puts the dividend into AL: AL = 0010 1101b = 2Dh. MOV CX, 8 sets up the loop counter; there will be one pass for each of the eight bits of AL. SHR AL, 1 shifts all the bits of AL one place to the right. A 0 enters the leftmost bit and the rightmost bit falls into CF. As a result AL holds the quotient and CF holds the remainder.
RCR BL, 1 (rotate through carry right) rotates BL together with CF like a 9-bit ring. The bit in CF enters bit 7 of BL, and bit 0 of BL goes out into CF. In this way the remainder produced by SHR is placed at the far left of BL. In every pass the old remainders in BL move one place right and the new one enters at the far left. LOOP bit decrements CX; if CX is not zero it returns to the label bit. This instruction does the job of “decrement CX, jump if not zero” in a single instruction and changes no flags.
| Pass | Quotient | SHR remainder | AL | BL (binary) | BL | CX |
|---|---|---|---|---|---|---|
| start | — | — | 2Dh | 0000 0000 | 00h | 8 |
| 1 | 45 ÷ 2 = 22 | 1 | 16h | 1000 0000 | 80h | 7 |
| 2 | 22 ÷ 2 = 11 | 0 | 0Bh | 0100 0000 | 40h | 6 |
| 3 | 11 ÷ 2 = 5 | 1 | 05h | 1010 0000 | A0h | 5 |
| 4 | 5 ÷ 2 = 2 | 1 | 02h | 1101 0000 | D0h | 4 |
| 5 | 2 ÷ 2 = 1 | 0 | 01h | 0110 1000 | 68h | 3 |
| 6 | 1 ÷ 2 = 0 | 1 | 00h | 1011 0100 | B4h | 2 |
| 7 | 0 ÷ 2 = 0 | 0 | 00h | 0101 1010 | 5Ah | 1 |
| 8 | 0 ÷ 2 = 0 | 0 | 00h | 0010 1101 | 2Dh | 0 |
Table 1.2.7 gives the eight passes. The program does not clear BL; the table assumes BL is 0 at the start. The result does not depend on this assumption: in eight passes all the old bits of BL go out into CF and are overwritten by the remainder of the next SHR. In every pass RCR shifts bit 0 of BL out into CF. This bit is always 0 until the eighth pass, so at the moment of LOOP CF appears as 0 in every pass. CF = 1 is seen only in the short moment between SHR and RCR: in passes 1, 3, 4, and 6. The first remainder reaches bit 0 of BL by shifting right eight times over the eight passes. The last remainder is placed in bit 7 of BL. When the program ends, BL = 0010 1101b = 2Dh = 45.
SHR AL, 1: 45 ÷ 2 = 22 (AL = 16h), and the dropped bit gives CF = 1. On the right when the loop ends: AL = 0, BL = 0010 1101b = 2Dh.The result may look surprising at first: the program took 45 and produced 45 again. That is exactly what makes it instructive. AL already holds a binary number; to “convert it to binary” there is no need to rewrite its bits. The program shows that the remainders of division by 2 are the very bits of the number. Arranged from last to first, the remainders reveal the binary representation of the number. The same idea is used to process the bits of a number one at a time: the bit dropped by SHR is read from CF and a decision is made with JC or JNC.
Using ROR instead of RCR. ROR BL, 1 rotates BL independently of CF: bit 0 moves to bit 7 and is only copied to CF. The remainder SHR dropped into CF never enters BL; the program merely rotates BL’s initial value. To carry the remainder, the rotation must go through the carry (RCR), or a separate instruction that reads CF after SHR must be used.
1.2.3.5The fractional part: multiplying by 2
The positional formula extends to the right of the radix point too. The weights of the digits after the point are negative powers of the base. In decimal, 0.375 = 3 × 10−1 + 7 × 10−2 + 5 × 10−3. In binary, the weights after the point go 2−1 = 0.5, 2−2 = 0.25, 2−3 = 0.125, 2−4 = 0.0625. 0.101b = 0.5 + 0.125 = 0.625.
The multiplication method converts a decimal fraction between 0 and 1 to binary. The fraction is multiplied by 2; the integer part of the product (0 or 1) becomes the next fraction bit. The process continues with the fractional part of the product. It stops when the fraction becomes 0 or the desired number of bits is reached. The bits are read from top to bottom, that is, in the order they were produced: the first bit is the 2−1 place.
The justification of the method mirrors the division method. Write x = 0.f1f2f3… (binary). 2x shifts the point one place to the right: f1.f2f3…. The integer part of the product is f1, and the fractional part is the number made of the remaining bits. Each multiplication moves one bit to the left of the point. In division the first remainder was the lowest digit; in multiplication the first integer part is the highest fractional digit. This is why the reading direction is reversed.
Let us convert 0.625 to binary.
- 0.625 × 2 = 1.25: integer part 1 (the 2−1 bit); continue with fraction 0.25.
- 0.25 × 2 = 0.5: integer part 0 (the 2−2 bit); fraction 0.5.
- 0.5 × 2 = 1.0: integer part 1 (the 2−3 bit); fraction 0, stop.
Reading the bits from top to bottom gives 0.101b. Check: 1/2 + 1/8 = 0.5 + 0.125 = 0.625.
For a number that has both an integer and a fractional part, the two parts are converted separately and combined. For 25.625, since 25 = 11001b (by the division method) and 0.625 = 0.101b, 25.625 = 11001.101b.
Fractional binary numbers are converted to hexadecimal by grouping in fours as well. The only difference is that the groups are formed outward from the point in both directions. The integer part is grouped from the point to the left and the fractional part from the point to the right. In the fractional part, missing bits are added as 0s on the right; a zero added to the right of the point does not change the value. For 1101.011b the groups are 1101 and 0110, and the result is D.6h.
1.2.3.6Repeating fractions: 0.1
Not every decimal fraction can be written finitely in binary. 1/3 goes on forever in decimal as 0.333…; in the same way 0.1 goes on forever in binary. The multiplication method shows this clearly.
Let us convert 0.1 to binary.
- 0.1 × 2 = 0.2 → bit 0; fraction 0.2.
- 0.2 × 2 = 0.4 → bit 0; fraction 0.4.
- 0.4 × 2 = 0.8 → bit 0; fraction 0.8.
- 0.8 × 2 = 1.6 → bit 1; fraction 0.6.
- 0.6 × 2 = 1.2 → bit 1; fraction 0.2.
- 0.2 × 2 = 0.4 → bit 0; the second step repeats.
After the fifth step the fraction returned to 0.2. 0.2 had been seen at the second step; from here on steps 2–5 repeat forever, and the bit pattern 0011 recurs. The result is 0.1 = 0.0 0011 0011 0011…b. If it is stored with 8 fraction bits, 0.0001 1001b = 0.097 656 25 is obtained.
A single rule decides which fractions can be written finitely. If a fraction in lowest terms is p/q, then for it to be finite in binary, q must be a power of 2. 0.625 = 5/8, and since 8 = 2³ it is written exactly with three bits. 0.1 = 1/10, and 10 has the factor 5; so it is not finite. The same rule holds in the decimal system: fractions whose denominator contains only the factors 2 and 5 are finite, and 1/3 is infinite.
The practical consequence of this rule is important. Because a computer uses a limited number of bits, it can store values like 0.1 only approximately; the extra bits are cut off or rounded. In the IEEE 754 floating-point format too, 0.1 is stored not exactly but approximately. This is why in many programming languages 0.1 + 0.2 does not come out exactly equal to 0.3. In applications such as money, where decimal fractions must be kept exactly, BCD or an integer number of cents is used.
Reading the fraction bits from bottom to top, as in the division method. For 0.625 the bits come out in the order 1, 0, 1, and because it is symmetric, the wrong reading goes unnoticed. For 0.375, however, the bits are 0, 1, 1: the correct result is 0.011b = 0.375; the reverse reading gives 0.110b = 0.75. In division the remainders are read in reverse, in multiplication the integer parts are read straight.
1.2.3.7Using the conversions together
The base converter in the slides shows an entered number in all four bases at once and lists the division steps for the chosen base. The route to follow when doing the same job by hand depends on the source and the target. Table 1.2.8 summarizes the shortest routes.
| Source → target | Method |
|---|---|
| binary/hexadecimal/octal → decimal | positional formula: sum of digit × weight |
| decimal → hexadecimal | divide by 16 and take remainders; for fractions, multiply by 16 |
| decimal → binary | first to hexadecimal, then expand each digit to 4 bits; or divide by 2 |
| binary ↔ hexadecimal | groups of four from the right; for fractions, outward from the point |
| binary ↔ octal | groups of three from the right |
| hexadecimal ↔ octal | via binary: first expand to 4 bits, then group in threes |
Let us write 2024 in hexadecimal, binary, and octal. 2024 ÷ 16 = 126, remainder 8; 126 ÷ 16 = 7, remainder 14 (E); 7 ÷ 16 = 0, remainder 7. The result is 7E8h. Each digit is expanded to four bits: 0111 1110 1000b. For octal, the same bits are grouped in threes from the right: 011 111 101 000 → 3750o. Check: 7 × 256 + 14 × 16 + 8 = 1792 + 224 + 8 = 2024 and 3 × 512 + 7 × 64 + 5 × 8 + 0 = 2024.
1.2.4Signed numbers
Up to here all numbers were zero or positive. Real programs, however, also work with negative values such as temperature differences, debts, and changes of direction. On paper a negative number is written with a minus sign in front. A register has no separate place for a minus sign; it has only bits. This section examines how negative numbers can be represented with bits and treats in detail the two’s complement representation the 8086 uses.
1.2.4.1Pattern and interpretation
Is 0FFh positive or negative? This question cannot be answered by looking at the bit pattern. The pattern 1111 1111 is 255 if read as unsigned and −1 if read in two’s complement. The processor does not know which of the two interpretations is meant, and it does not need to. The interpretation is determined by the instruction that uses the pattern, or by the programmer.
In the unsigned interpretation, n-bit patterns represent the values between 0 and 2n − 1. In the signed interpretation half of the patterns are set aside for negative numbers. In the two’s complement representation used by the 8086, the negative number −x is written with the pattern of the unsigned value 2n − x.
With 8 bits there are 256 different patterns. In two’s complement the first 128 of them (00h … 7Fh, that is, 0 … 127) represent zero and the positive numbers. The next 128 (80h … FFh, that is, unsigned 128 … 255) represent the negative numbers. To write −5, 5 is subtracted from the number of patterns: 256 − 5 = 251 = FBh. For −1, 256 − 1 = 255 = FFh; for −128, 256 − 128 = 128 = 80h. Figure 1.2.20 shows the two interpretations of the 256 patterns on the same axis.
The two interpretations share a property: in all negative numbers the most significant bit is 1, and in all positive ones it is 0. That is why the MSB is called the sign bit. After every arithmetic and logic operation the 8086 copies the MSB of the result into the sign flag (SF). If SF = 1, the result is negative in the signed interpretation.
1.2.4.2The number circle
A fixed-width register behaves not like a line but like a circle. Consider a 4-bit register. Starting at 0000 and adding 1 repeatedly, we reach 0001, 0010, … 1111. Adding 1 to 1111 gives 1 0000; the fifth bit does not fit in the register and the register returns to 0000. Figure 1.2.21 arranges the sixteen patterns on a circle. Moving one step clockwise is adding 1, and one step counterclockwise is subtracting 1.
The circle clearly shows two “break” points. The first is between 1111 and 0000. In the unsigned interpretation this is where the count jumps from 15 to 0. If an addition crosses this point, the result did not fit in the unsigned interpretation, and the 8086 reports this with the carry flag (CF). The second is between 0111 and 1000. In the signed interpretation this is where the count jumps from +7 to −8. If an operation crosses this point, the result did not fit in the signed interpretation, and the 8086 reports this with the overflow flag (OF).
The most important lesson of the circle is this: the addition and subtraction circuit is the same for both interpretations. Moving one step on the circle does not depend on which interpretation the pattern is read with. The operation 1011 + 0001 = 1100 is 11 + 1 = 12 in the unsigned interpretation and −5 + 1 = −4 in the signed one; both results are correct. The processor uses a single adder and sets separate flags for the two interpretations. It is up to the program to decide which flag to look at.
1.2.4.3Three signed representations
Two’s complement is not the only way to represent negative numbers. Three representations have been used historically. Table 1.2.9 compares the sixteen 4-bit patterns under four interpretations.
| Binary | Unsigned | Sign-magnitude | One’s complement | Two’s complement |
|---|---|---|---|---|
0000 | 0 | 0 | 0 | 0 |
0001 | 1 | 1 | 1 | 1 |
0010 | 2 | 2 | 2 | 2 |
0011 | 3 | 3 | 3 | 3 |
0100 | 4 | 4 | 4 | 4 |
0101 | 5 | 5 | 5 | 5 |
0110 | 6 | 6 | 6 | 6 |
0111 | 7 | 7 | 7 | 7 |
1000 | 8 | −0 | −7 | −8 |
1001 | 9 | −1 | −6 | −7 |
1010 | 10 | −2 | −5 | −6 |
1011 | 11 | −3 | −4 | −5 |
1100 | 12 | −4 | −3 | −4 |
1101 | 13 | −5 | −2 | −3 |
1110 | 14 | −6 | −1 | −2 |
1111 | 15 | −7 | −0 | −1 |
In the sign-magnitude representation the top bit gives the sign and the remaining bits give the absolute value of the number. In 4 bits, 0101 = +5 and 1101 = −5. It is the direct counterpart of the minus sign on paper.
Sign-magnitude is the easiest to read, but it has two serious problems. First, zero has two representations: 0000 = +0 and 1000 = −0. To test whether a number is zero, both patterns have to be checked. Second, the addition circuit gets complicated. In +5 + (−3), adding 0101 and 1011 directly gives 1 0000, which is not the expected +2. The adder would first have to compare the signs and then add the magnitudes or subtract the smaller from the larger. This representation is not used for integers today. The sign bit of floating-point numbers is based on the same idea.
1.2.4.4One’s complement
In the one’s complement representation the negative of a number is obtained by inverting all the bits of the number (0 → 1, 1 → 0). In n bits the pattern of −x is (2n − 1) − x. On the 8086 the NOT instruction produces the one’s complement of an operand.
An 8-bit example: +45 = 0010 1101b. Inverting all the bits gives 1101 0010b = D2h. In one’s complement this pattern is −45. The same pattern in two’s complement represents −46; the two representations differ by exactly one. Figure 1.2.22 shows the operation bit by bit.
One’s complement largely solves the addition problem of sign-magnitude, but it leaves two flaws. Zero still has two representations: 0000 0000 = +0 and 1111 1111 = −0. Also, if a carry comes out of the top bit in an addition, that carry has to be added back to the lowest bit of the result; this is called the end-around carry. In 4 bits, −2 + 5: 1101 + 0101 = 1 0010. Adding the carried 1 back gives 0010 + 1 = 0011 = 3. Some old computers (the CDC 6600, UNIVAC 1100) used this representation. Today one’s complement appears not as a number representation by itself but as an intermediate step of two’s complement and as the bitwise NOT operation.
1.2.4.5Two’s complement
Two’s complement removes both flaws of one’s complement in a single move: 1 is added to the inverted pattern. This addition eliminates the −0 pattern and removes the need for the end-around carry.
The two’s complement of a number is found by first inverting all its bits and then adding 1 to the result: −x = NOT x + 1. In n bits this pattern is 2n − x. On the 8086 the NEG instruction produces the two’s complement of its operand in one step; it does the operation as the subtraction 0 − x.
It is easy to show that the two formulas give the same pattern. The pattern in which all n bits are 1 is 2n − 1. Inverting the bits of a number is the same as subtracting it from this pattern, because 1 − 0 = 1 and 1 − 1 = 0 and no borrow is needed in any position. Hence NOT x = (2n − 1) − x and NOT x + 1 = 2n − x.
Let us find the 8-bit two’s complement representation of −45. +45 = 0010 1101b. Inverting all the bits gives 1101 0010b. Adding 1 gives 1101 0011b = D3h. Check: D3h = 211 = 256 − 45. A second check is done by addition: D3h + 2Dh = 100h; in 8 bits the result is 00h, that is, −45 + 45 = 0.
There is a faster shortcut for hand calculation. Starting from the right, the bits up to and including the first 1 are copied unchanged, and all the remaining bits on the left are inverted. For 0010 1101 the rightmost bit is already 1; it stays as it is, and the seven bits on the left are inverted: 1101 0011. For 0001 1000 (24) the first 1 from the right is at bit 3: the 1000 on the right stays unchanged and the 0001 on the left is inverted: 1110 1000 = E8h = 256 − 24. The reason for the shortcut is that adding 1 clears the run of 1s on the right and turns the first 0 into a 1.
Two’s complement has two important properties. First, the two’s complement of a number’s two’s complement is the number itself: 2n − (2n − x) = x. The two’s complement of D3h is 2Dh again. So the magnitude of a negative number is found with the same operation. Second, zero has a single representation. The two’s complement of 0000 0000 is 1111 1111 + 1 = 1 0000 0000; when the ninth bit is dropped, 0000 0000 remains. The −0 pattern of one’s complement (1111 1111) is −1 in two’s complement.
In two’s complement the signed value of a pattern can also be computed directly. The weight of the MSB is taken as negative and the other bits are added as usual. In 8 bits the weights are −128, 64, 32, 16, 8, 4, 2, 1. For D3h = 1101 0011b this gives −128 + 64 + 16 + 2 + 1 = −45. This interpretation is useful for fixed-point fractions too.
1.2.4.6Code trace: NOT + 1 versus NEG
The following program computes the two’s complement of the same number in two ways and compares the results. Then it adds −45 + 45 and repeats the same operation in 16 bits. The program is a good example for seeing the effect of each instruction on the flags.
ORG 100h
MOV AL, 45 ; +45
MOV BL, AL
NOT BL ; ones' comp.
INC BL ; + 1
NEG AL ; one instr.
CMP AL, BL ; equal?
ADD AL, 45 ; -45 + 45
MOV AX, 45
NEG AX ; -45 in 16 bits
RETMOV AL, 45 loads 2Dh into AL; MOV BL, AL copies the same value into BL. MOV instructions change no flags. NOT BL inverts all the bits of BL: BL = D2h. NOT affects no flag either. INC BL adds 1 to BL: BL = D3h. INC sets the ZF, SF, OF, AF, and PF flags but does not touch CF. The result is not zero (ZF = 0) and its MSB is 1 (SF = 1).
NEG AL computes AL as 0 − AL and gives the same result in one instruction: AL = D3h. NEG sets CF = 1 if the operand is not zero, because subtracting a nonzero number from 0 requires a borrow in the unsigned interpretation. CMP AL, BL computes the difference AL − BL but does not store the result. Since D3h − D3h = 0, ZF = 1, CF = 0, SF = 0. ZF = 1 shows that the two routes produced the same bit pattern.
ADD AL, 45 adds −45 and +45. D3h + 2Dh = 100h. The ninth bit does not fit in AL and falls into CF: CF = 1. AL = 00h; ZF = 1. In the signed interpretation the result is correct (−45 + 45 = 0), so OF = 0. This line shows that in two’s complement CF = 1 does not mean an error. MOV AX, 45 loads 002Dh into AX. NEG AX computes the 16-bit two’s complement: 65,536 − 45 = 65,491 = FFD3h. The low byte is again D3h; the high byte has become FFh.
| Instruction | AX | BL | CF | ZF | SF | OF | Note |
|---|---|---|---|---|---|---|---|
MOV AL, 45 | 002Dh | 00h | 0 | 0 | 0 | 0 | AL = +45 |
MOV BL, AL | 002Dh | 2Dh | 0 | 0 | 0 | 0 | copy |
NOT BL | 002Dh | D2h | 0 | 0 | 0 | 0 | one’s complement; flags unchanged |
INC BL | 002Dh | D3h | 0 | 0 | 1 | 0 | D3h = −45; CF untouched |
NEG AL | 00D3h | D3h | 1 | 0 | 1 | 0 | 0 − 2Dh; operand ≠ 0 → CF = 1 |
CMP AL, BL | 00D3h | D3h | 0 | 1 | 0 | 0 | difference 0 → equal |
ADD AL, 45 | 0000h | D3h | 1 | 1 | 0 | 0 | D3h + 2Dh = 100h |
MOV AX, 45 | 002Dh | D3h | 1 | 1 | 0 | 0 | MOV leaves the flags alone |
NEG AX | FFD3h | D3h | 1 | 0 | 1 | 0 | 65,536 − 45 = FFD3h |
NEG AL: AL = D3h, BL = D3h, CF = 1, SF = 1. On the right after NEG AX: AX = FFD3h (unsigned 65,491, signed −45).The last two rows show how the same number is written at different widths. −45 is D3h in 8 bits and FFD3h in 16 bits. The low byte of the 16-bit representation is the same as the 8-bit representation; the high byte consists only of copies of the sign bit (FFh). This observation is the basis of sign extension.
Confusing NOT with NEG. NOT AL gives the one’s complement, and the result is 1 less than the true negative: with AL = 2Dh, NOT AL = D2h = −46. To change a number’s sign, NEG must be used, or INC must be added after NOT. Another misconception is to take CF = 1 after NEG for an error; NEG always gives CF = 1 unless the operand is zero.
1.2.4.7−5 + 5 = 0
The most basic rule a negative-number representation must satisfy is the equality −x + x = 0 from mathematics. In two’s complement −5 = FBh = 1111 1011b. Adding 5 = 0000 0101b gives the sum 1 0000 0000b = 256. The ninth bit does not fit in the byte and is dropped; all of the remaining 8 bits are zero. Figure 1.2.25 shows the addition column by column.
This addition is an example of how the same adder circuit gives the correct result for both interpretations. In the unsigned interpretation the result of 251 + 5 = 256 did not fit in 8 bits; CF = 1 reports this. In the signed interpretation −5 + 5 = 0 is correct and OF = 0. This is why two’s complement was chosen: no separate circuit is needed for negative numbers, and the adder works without knowing the meaning of the patterns. The mathematical reason is that an n-bit addition is really done modulo 2n. In this modulus 2n − x and −x are in the same class.
1.2.4.8Signed ranges and sign extension
Table 1.2.11 gives the unsigned and signed ranges of 8-, 16-, and 32-bit numbers. At every width half of the patterns are negative.
| Width | Number of patterns | Unsigned | Signed | Negative patterns |
|---|---|---|---|---|
| 8 bits | 256 | 0 … 255 | −128 … +127 | 80h … FFh |
| 16 bits | 65,536 | 0 … 65,535 | −32,768 … +32,767 | 8000h … FFFFh |
| 32 bits | 4,294,967,296 | 0 … 4,294,967,295 | −2,147,483,648 … +2,147,483,647 | 80000000h … FFFFFFFFh |
The range is not symmetric: the negative side has one more value than the positive side. The reason is that zero sits on the positive side. In 8 bits there are 128 negative and 128 zero-or-positive patterns; the positives are 1 … 127 and the negatives are −1 … −128. This asymmetry has an interesting consequence: the positive counterpart of −128 does not fit in 8 bits. If the two’s complement of 80h is taken with NEG, 0111 1111 + 1 = 1000 0000 = 80h comes out; the result does not change and the 8086 reports the overflow with OF = 1.
Sign extension carries a signed value into a wider register without changing its value: the old sign bit is copied into all of the newly added upper bits. Zero extension, by contrast, sets the upper bits to 0 and is correct for unsigned values. On the 8086, CBW sign-extends AL into AX and CWD sign-extends AX into DX:AX.
Why extension is done with the sign bit can be seen from the two’s complement formula. −5 is 256 − 5 = FBh in 8 bits and 65,536 − 5 = FFFBh in 16 bits. The only difference between the two patterns is that the upper byte is FFh. For a positive number the upper byte is 00h: +5 is 05h and 0005h. In both cases the upper bits are copies of the sign bit. If FBh were zero-extended, 00FBh = +251 would result, and the value −5 would be lost.
CBW executes with AL = 9Ch (−100). The MSB of AL is 1, so AH = FFh and AX = FF9Ch results. Check: 65,536 − 100 = 65,436 = FF9Ch. Had AL been 64h (+100), the MSB would be 0, so AH = 00h and AX = 0064h. CWD does the same job one width up: if AX = FF9Ch, DX = FFFFh.
1.2.4.9Fixed-point signed fractions
Floating-point hardware is not always available for fractional numbers. The 8086 has no floating-point instruction; many small microcontrollers do not either. In such systems fractions are kept in integer registers as fixed-point numbers. The position of the point is decided in advance and is stored nowhere.
A fixed-point number is a binary number whose radix point is at a predetermined position. A number in Qm.f format consists of m integer bits, including the sign bit, and f fraction bits. Reading the pattern as an integer and dividing by 2f gives the value of the number.
Consider the 8-bit Q5.3 format: the last three bits are the fraction. The place weights from left to right are −16, 8, 4, 2, 1, ½, ¼, ⅛. The weight of the leftmost bit is negative, as in two’s complement. The representable values are between −16 and +15.875, and the difference between two consecutive values is 1/8 = 0.125.
Let us write −6.75 in Q5.3 format. First +6.75 is written: 6.75 = 4 + 2 + ½ + ¼, that is, 00110.110b = 36h. For the negative, the two’s complement is taken, ignoring the point. Inverting 0011 0110 gives 1100 1001; adding 1 gives 1100 1010 = CAh. With the point put back, 11001.010b is read.
The check is done with the weights: −16 + 8 + 1 + ¼ = −6.75. There is a shorter way too: multiply the number by 2³ = 8 and treat it as an integer. −6.75 × 8 = −54 and 256 − 54 = 202 = CAh.
The main advantage of fixed-point numbers is that addition is ordinary integer addition. To the processor CAh is an ordinary byte; the position of the point is only the programmer’s convention. In the operation −6.75 + 2.5, 2.5 × 8 = 20 = 14h. CAh + 14h = DEh. DEh = 11011.110b, and by the weights −16 + 8 + 2 + 1 + ½ + ¼ = −4.25; this is the expected result. No extra hardware is needed for addition and subtraction. In multiplication, however, the number of fraction bits of the result doubles, and the result is rescaled by shifting right f bits.
The bit explorer in the slides shows the unsigned, signed, BCD, and Gray-code interpretations of an 8-bit pattern together. Watching how the four interpretations change when one of the bits is changed reinforces the distinction between pattern and interpretation.
1.2.5Binary and hexadecimal arithmetic
The arithmetic logic unit (ALU) of a microprocessor does addition, subtraction, and bitwise operations on binary numbers. The programmer, however, often reads the results in hexadecimal. This section explains how to add and subtract by hand in the two bases, why subtraction reduces to addition, and how the CF and OF flags are set after an operation.
1.2.5.1Binary addition and the full adder
Binary addition is done the same way as decimal addition: the numbers are written one under the other, you start at the lowest digit, and the columns are added in turn. The difference is that when a column sum reaches 2 it turns into a carry. For two digits in one column there are four cases: 0 + 0 = 0, 0 + 1 = 1, 1 + 0 = 1, and 1 + 1 = 10b. In the last case 0 is written in the column and a carry of 1 is passed to the next column. When the carry from the previous column is added too, the sum can be 3 (11b); in that case 1 is written in the column and a carry of 1 again comes out.
| a | b | cin | s | cout |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 1 | 1 | 0 |
| 0 | 1 | 0 | 1 | 0 |
| 0 | 1 | 1 | 0 | 1 |
| 1 | 0 | 0 | 1 | 0 |
| 1 | 0 | 1 | 0 | 1 |
| 1 | 1 | 0 | 0 | 1 |
| 1 | 1 | 1 | 1 | 1 |
Table 1.2.12 gives all the cases of a single column. This table is the truth table of the full adder circuit known from digital design. The sum bit is the XOR of the three inputs: s = a ⊕ b ⊕ cin. The carry out is 1 when at least two of the inputs are 1: cout = ab + cin(a ⊕ b). If eight full adders are chained, with the carry out of each connected to the carry in of the next, an 8-bit adder results. This structure is called a ripple-carry adder. The carry out of the last full adder is the bit written into the CF flag on the 8086.
The ripple-carry adder has a weakness: the result of the top bit has to wait for the carry to pass through all the gates from bottom to top. In a 16-bit addition the delay is about 16 times that of a single full adder. Fast processors therefore use circuits that compute the carry in advance (carry-lookahead). The logic is the same; only the carries are computed in parallel.
Let us add 110001101b (397) and 100001011b (267). The columns are numbered from right to left.
- Digit 0: 1 + 1 = 2 → write 0, carry 1.
- Digit 1: 0 + 1 + 1 (carry) = 2 → write 0, carry 1.
- Digit 2: 1 + 0 + 1 (carry) = 2 → write 0, carry 1.
- Digit 3: 1 + 1 + 1 (carry) = 3 → write 1, carry 1.
- Digit 4: 0 + 0 + 1 (carry) = 1 → write 1, no carry.
- Digit 5: 0 + 0 = 0 → write 0.
- Digit 6: 0 + 0 = 0 → write 0.
- Digit 7: 1 + 0 = 1 → write 1.
- Digit 8: 1 + 1 = 2 → write 0, carry 1.
- Digit 9: only the carry 1 → write 1.
The result is 1010011000b. Check: 512 + 128 + 16 + 8 = 664 = 397 + 267. The numbers added were 9 bits and the result is 10 bits. In a 9-bit adder the topmost 1 does not fit and goes out as a carry.
1.2.5.2Binary subtraction: adding the complement
Subtraction can also be done column by column by borrowing. Processors, however, usually do not use a separate subtractor circuit. Subtraction is turned into addition: A − B = A + (−B). −B is the two’s complement of B, and the two’s complement is found by inverting the bits and adding 1. Inverting the bits is done with one XOR gate per bit, and adding 1 is done by setting the carry in of the lowest full adder to 1. In this way the same adder both adds and subtracts.
Let us compute 1011 − 0110 (11 − 6) in 4 bits. A = 1011, B = 0110. The bits of B are inverted: 1001. Adding 1 gives 1010; this is −6 in 4 bits. It is added to A: 1011 + 1010 = 10101. The result is 5 bits. The leftmost 1, which does not fit in 4 bits, is dropped and 0101 = 5 remains. Check: 11 − 6 = 5.
In this example the carry that was dropped is 1 and the result is correct. What would happen if A < B? For 0110 − 1011 (6 − 11), the two’s complement of 1011 is 0101. 0110 + 0101 = 1011, and no carry comes out. 1011 is −5 in the signed interpretation; the correct result is also −5. The absence of a carry shows that in the unsigned interpretation the subtraction needed a borrow, that is, A is smaller than B.
The 8086 stores this relationship inverted in the CF flag. After SUB and CMP, CF shows whether a borrow was taken in the unsigned interpretation. If a carry came out in addition by complement, there is no borrow and CF = 0. If no carry came out, there is a borrow and CF = 1. Thanks to this rule, CF = 1 after CMP AX, BX means AX < BX in the unsigned interpretation. JB (“jump if below”) looks at exactly this flag.
1.2.5.3Hexadecimal addition
Hexadecimal numbers are also added column by column. The values of the digits are thought of in decimal (A = 10, …, F = 15). If a column sum is less than 16 it is written directly. If it is 16 or more, 16 is subtracted from the sum, the remainder is written in the column, and a carry of 1 is passed to the left. The rule is the same as in decimal addition; only the threshold is 16 instead of 10.
Let us find the sum 9A7Ch + 5B96h.
- C + 6 = 12 + 6 = 18 ≥ 16 → 18 − 16 = 2, write 2, carry 1.
- 7 + 9 + 1 = 17 ≥ 16 → 17 − 16 = 1, write 1, carry 1.
- A + B + 1 = 10 + 11 + 1 = 22 ≥ 16 → 22 − 16 = 6, write 6, carry 1.
- 9 + 5 + 1 = 15 < 16 → write F, no carry.
The result is F612h. Check in decimal: 9A7Ch = 39,548, 5B96h = 23,446, and 39,548 + 23,446 = 62,994 = F612h. On the 8086, with AX = 9A7Ch and BX = 5B96h, ADD AX, BX gives the same result. Since no carry comes out of the leftmost column, CF = 0.
There is one more detail in this addition. In the signed interpretation 9A7Ch is negative (MSB = 1) and 5B96h is positive. The sum of two numbers of different signs never produces signed overflow; so OF = 0. F612h is −2542 in the signed interpretation: −25,988 + 23,446 = −2542.
1.2.5.4Hexadecimal subtraction
In hexadecimal subtraction, if the upper digit is smaller than the lower one, 1 is borrowed from the column on the left. The borrowed 1 is worth 16 in the column on the right. The digit of the lending column decreases by 1.
Let us find the difference 9A7Ch − 5B96h.
- C − 6 = 12 − 6 = 6; no borrow.
- 7 − 9 is not possible: borrow from the left. 7 + 16 − 9 = 14 = E; the A on the left drops to 9.
- 9 − B is not possible: borrow again. 9 + 16 − 11 = 14 = E; the 9 on the left drops to 8.
- 8 − 5 = 3; no borrow.
The result is 3EE6h. Check: 39,548 − 23,446 = 16,102 = 3EE6h. Since no borrow is needed in the leftmost column, CF = 0 after SUB AX, BX.
1.2.5.515’s and 16’s complement
The hexadecimal counterparts of one’s and two’s complement in binary are the 15’s and 16’s complement. They turn hexadecimal subtraction into addition, just as in binary.
The 15’s complement of a k-digit hexadecimal number is found by subtracting each digit from F and equals 16k − 1 − x. The 16’s complement is found by adding 1 to the 15’s complement and equals 16k − x. Since a 4-digit hexadecimal number is 16 bits, the 16’s complement is the same pattern as the 16-bit two’s complement.
The 15’s complement of 5B96h: F − 5 = A, F − B = 4, F − 9 = 6, F − 6 = 9 → A469h. Its 16’s complement is A469h + 1 = A46Ah; this equals 10000h − 5B96h. Now 9A7Ch − 5B96h is computed as 9A7Ch + A46Ah: the sum is 13EE6h. The 1 beyond four digits is dropped and 3EE6h remains. The same result as direct subtraction has been found.
Let us compute 5B96h − 9A7Ch in the opposite direction. The 16’s complement of 9A7Ch is 10000h − 9A7Ch = 6584h. 5B96h + 6584h = C11Ah, and no carry beyond four digits comes out. The absence of a carry shows that the result is negative. To find the magnitude, the 16’s complement of C11Ah is taken: 10000h − C11Ah = 3EE6h. The result is −3EE6h, that is, −16,102.
On the 8086, with AX = 5B96h and BX = 9A7Ch, SUB AX, BX gives AX = C11Ah directly. Because a borrow occurred, CF = 1. C11Ah is −16,102 in the signed interpretation; if the programmer reads the result as signed, no extra step is needed. If it is read as unsigned, CF = 1 says the result is meaningless, because a larger number was subtracted from a smaller one.
1.2.5.6Carry and signed overflow
In a fixed-width register the result of any operation may not fit. Not fitting happens in two different ways, and the 8086 reports them with two separate flags. Confusing these two flags is one of the most common mistakes in assembly programming.
The carry flag (CF) shows that in the unsigned interpretation the result did not fit in the destination: in addition a carry came out of the top bit, in subtraction a borrow was taken. The overflow flag (OF) shows that in the signed interpretation the result did not fit in the destination’s range. The hardware sets OF as follows: if the carry into the sign bit and the carry out of the sign bit differ, OF = 1.
The sign of signed overflow is that the sign of the result comes out opposite to what is expected. If the sum of two positive numbers comes out negative, or the sum of two negative numbers comes out positive, overflow has occurred. The sum of two numbers of different signs, however, never overflows: the result always lies between the two numbers and so within the range. In subtraction the situation is reversed: since A − B = A + (−B), the difference of numbers with different signs can overflow, and the difference of numbers with the same sign cannot. Table 1.2.13 gives the six cases with 8-bit examples.
| Operation | Signs | Example | Signed interpretation | OF | CF |
|---|---|---|---|---|---|
| A + B | + and + | 50h + 40h = 90h | 80 + 64 → −112 (wrong) | 1 | 0 |
| A + B | − and − | 9Ch + CEh = 6Ah | −100 + (−50) → +106 (wrong) | 1 | 1 |
| A + B | different | 64h + CEh = 32h | 100 + (−50) = 50 | 0 | 1 |
| A − B | + minus − | 64h − CEh = 96h | 100 − (−50) → −106 (wrong) | 1 | 1 |
| A − B | − minus + | 9Ch − 32h = 6Ah | −100 − 50 → +106 (wrong) | 1 | 0 |
| A − B | same | 9Ch − CEh = CEh | −100 − (−50) = −50 | 0 | 1 |
The CF column of the table shows that the two flags are independent of each other. In the first row CF = 0 but OF = 1: 80 + 64 = 144 fits in 255 in the unsigned interpretation and exceeds 127 in the signed one. In the third row CF = 1 but OF = 0: in the unsigned interpretation 100 + 206 = 306 does not fit in a byte, and in the signed interpretation 100 − 50 = 50 is correct. Which flag is meaningful depends on how the programmer interprets the numbers. A program working with unsigned numbers looks at CF, and one working with signed numbers looks at OF.
Let us apply the hardware rule to 50h + 40h. When 0101 0000 + 0100 0000 is added, 1 + 1 = 10b occurs at bit 6: a carry of 1 goes from bit 6 into bit 7 (the sign bit). At bit 7, 0 + 0 + 1 = 1; no carry comes out of the sign bit. The carry in is 1 and the carry out is 0; since they differ, OF = 1. Because the carry out is 0, CF = 0. The result is 1001 0000 = 90h.
For 9Ch + CEh, 1001 1100 + 1100 1110 is added. At bit 6, 0 + 1 + (0 from bit 5) = 1; no carry goes into the sign bit. At bit 7, 1 + 1 = 10b; a carry comes out. Because the carry in is 0 and the carry out is 1, OF = 1, and because the carry out is 1, CF = 1. The result is 0110 1010 = 6Ah.
The logic of the rule can be explained like this. The carry out of the sign bit shows unsigned overflow. The carry into the sign bit shows that the sum of the lower seven bits exceeded 127. With two positive numbers there is no carry out; if there is a carry in, the result has corrupted the sign bit. With two negative numbers there is always a carry out; if there is no carry in, the result has dropped the sign bit to 0. If the carry in and carry out are equal, the sign bit has stayed correct.
When numbers of different widths are to be added, the shorter one must first be sign-extended. Suppose FBh (−5) is to be added to 0100h (256). Sign-extending FBh gives FFFBh: FFFBh + 0100h = 1 00FBh, and the 16-bit result is 00FBh = 251. The correct result is also −5 + 256 = 251. Had FBh been zero-extended, 00FBh + 0100h = 01FBh = 507 would have come out, which is wrong. On the 8086 CBW does this job in one instruction.
Reading CF = 1 in every case as “the result is wrong.” When working with signed numbers CF is meaningless: in −5 + 5, CF = 1 but the result (0) is correct. Conversely, when working with unsigned numbers OF is meaningless: in 80 + 64, OF = 1 but the unsigned result (144) is correct. A flag is read only according to the interpretation the programmer has chosen.
1.2.5.7Constant expressions in the assembler
The emu8086 assembler accepts a set of operators in constant expressions. These operators make programs easier to write: a mask or an address difference can be written as an expression instead of being computed by hand. Table 1.2.14 lists the supported operators with examples.
| Operator | Meaning | Example → value | Run-time counterpart |
|---|---|---|---|
~ | inverts all the bits | ~0Fh → F0h (8 bits) | NOT |
* | multiplication | 3*4 → 12 | MUL |
/ | integer division | 17/5 → 3 | DIV (quotient) |
% | remainder | 17%5 → 2 | DIV (remainder) |
+ | addition | 40h+2 → 42h | ADD |
- | subtraction, unary minus | -5 → FBh | SUB, NEG |
<< | shift left | 1<<4 → 16 | SHL |
>> | shift right | 80h>>3 → 10h | SHR |
& | bitwise AND | 0F0h&3Ch → 30h | AND |
^ | bitwise XOR | 0Fh^05h → 0Ah | XOR |
| | bitwise OR | 0F0h|0Fh → FFh | OR |
These expressions are evaluated at assembly time. When MOV AX, 3*4+1 is written, the assembler computes 13 and puts the instruction MOV AX, 13 into the machine code. The processor does no multiplication while running. That is why expressions work only with constants: MOV AX, BX*2 is invalid, because the value of BX is not known at assembly time. At run time the same operations are done with the instructions in the last column of the table. To multiply BX by 2, for example, SHL BX, 1 is used.
1.2.6The bit in hardware
So far bits have been treated as abstract 0s and 1s. In a microprocessor, however, every bit is a physical quantity: the voltage on a line or the stable state of a circuit. This section explains how voltage levels correspond to bits and how bits are stored in flip-flops. The topics are familiar from digital design; here their relation to the 8086’s registers and clock signal is emphasized.
1.2.6.1Binary signals and voltage levels
The instructions and data of a program sit in memory as groups of digits. In circuits these digits exist as voltage and current. Digital computers use two kinds of signal: the high level represents 1 and the low level represents 0. In a circuit powered by 5 V like the 8086, the high level is close to 5 V and the low level close to 0 V.
The voltage does not have to be exactly 5 V or exactly 0 V. Each logic family defines threshold ranges for an input. In the TTL (transistor-transistor logic) family an input of 2.0 V or above is taken as 1, and an input of 0.8 V or below as 0. The region in between is undefined, and in a stably working circuit a signal is there only during a transition. On the output side the limits are tighter: a TTL output gives at least 2.4 V for 1 and at most 0.4 V for 0. The 0.4 V margin between output and input thresholds is the noise margin. Even if this much noise is added to the signal, the receiver reads the bit value correctly. This is why digital circuits are robust against noise. In an analog circuit every bit of noise added to the signal corrupts the value; in a digital circuit noise that does not cross the threshold leaves no trace.
The 8086’s address and data buses are made of lines like these. The 20 address lines carry 20 bits at the same time, and the 16 data lines carry 16 bits at the same time. When a MOV instruction reads a word from memory, the memory chip pulls each of the 16 data lines to a high or low level. The processor samples these levels at a specific moment of the clock and takes them into its register.
1.2.6.2The flip-flop
To hold a bit until the next operation, a circuit with memory is needed. A combinational circuit built from gates changes its output when its inputs change; it does not remember the past. Circuits with feedback do remember.
A flip-flop is the basic memory circuit that stores one bit and changes its state in step with the clock signal. It has two outputs: the stored bit Q and its complement Q′. The value at its input is loaded into the circuit at a specific moment of the clock signal and is held until the next such moment.
Figure 1.2.33 shows an SR flip-flop with a clock input. The heart of the circuit is two cross-coupled NOR gates. The output of each gate is fed back to the input of the other. This feedback creates two stable states: Q = 1, Q′ = 0 or Q = 0, Q′ = 1. While the inputs are 0 the circuit stays in the state it is in; it “remembers” the bit. The S and R inputs pass through AND gates with the clock signal. Thus the inputs take effect only while the clock is 1.
1.2.6.3Types of flip-flops
In practice four types of flip-flops are used. All store one bit; the meaning of their inputs differs. Table 1.2.15 summarizes the behavior of the four types.
| Type | Inputs | Behavior | Use |
|---|---|---|---|
| SR (set-reset) | S, R | S = 1 → Q = 1; R = 1 → Q = 0; S = R = 0 → no change | S = R = 1 is forbidden |
| D (data) | D | Q ← D | register and memory cell |
| JK | J, K | J = 1 → Q = 1; K = 1 → Q = 0; J = K = 0 → no change; J = K = 1 → Q toggles | has no forbidden state |
| T (toggle) | T | T = 1 → Q toggles; T = 0 → no change | counter, frequency divider |
In an SR flip-flop the input S = R = 1 is forbidden. In that case the outputs of both NOR gates become 0, and Q and Q′ stop being each other’s complement. If the inputs return to 0 at the same time, which state the circuit falls into depends on the gate delays and is unpredictable. The JK flip-flop turns this case into something useful: when J = K = 1, the output toggles at every clock pulse. This toggling is what makes the JK flexible. When the J and K inputs are tied together into a single T input, a T flip-flop results. The output of a T flip-flop held at T = 1 produces a full period every two clock pulses; that is, it divides the clock frequency by two. Chained T flip-flops form a binary counter.
In a JK flip-flop Q = 0 initially, and three rising clock edges arrive while J = K = 1 is held. At every edge the output toggles: 0 → 1 → 0 → 1. After three edges Q = 1. Had the number of edges been even, Q would be 0 again.
1.2.6.4The D flip-flop and the register
The type most used in microprocessors is the D flip-flop. It has a single data input, and at the rising edge of the clock the value on D is copied to Q. Figure 1.2.34 shows this behavior on a timing diagram.
In the diagram the D input changes several times between clock edges, but Q is unaffected by these changes. D is sampled only at the moment of the rising edge, and the value is held in Q until the next edge. This is a 1-bit memory. If 16 D flip-flops are placed side by side and driven by a common clock and a load signal, a 16-bit register results. The 8086’s registers such as AX and BX are built this way in principle. A MOV AX, BX instruction is the transfer of BX’s outputs over the internal data bus to AX’s D inputs and their loading into AX at a clock edge. Each flag in the flags register is also a flip-flop.
The clock signal determines when all these loads happen. All internal operations of the 8086 are divided into clock cycles. With a 5 MHz clock one clock cycle takes 1 / 5,000,000 s = 200 ns. How many cycles an instruction takes depends on how many internal steps it consists of. A register-to-register MOV takes 2 cycles and a 16-bit DIV takes 144–162 cycles. A memory read requires a bus cycle of at least 4 cycles (T1–T4).
1.2.7Floating-point numbers: IEEE 754
Because the position of the point is fixed, fixed-point representation can hold either very large or very small numbers, but not both together. In Q5.3 format the smallest step is 0.125 and the largest value is below 16. Scientific computation, however, needs both large numbers like 6 × 1023 and small ones like 1.6 × 10−19. When the idea of scientific notation is carried over to binary, the floating-point format results: a number is written as the product of a fraction and a power of 2, and the point “floats” according to the exponent.
1.2.7.1The single-precision format
An IEEE 754 single-precision floating-point number is 32 bits and consists of three fields: a 1-bit sign s (bit 31), an 8-bit exponent e (bits 30–23), and a 23-bit fraction (mantissa) f (bits 22–0). The exponent is stored with a bias of 127. The value of a normalized number is
value = (−1)s × 1.f × 2e − 127
Here the 1 is the hidden bit, which is not stored.
Three details of the format need explanation. First, the sign is a separate bit: floating-point numbers are stored with sign-magnitude logic, not two’s complement. To negate a number only bit 31 is inverted. Second, the exponent is stored biased: 127 is added to the true exponent. Exponents from −126 to +127 are thus written as unsigned numbers from 1 to 254. The benefit of the bias is that the patterns of two positive floating-point numbers can be compared like unsigned integers. Third, a normalized binary number always starts with 1: 1.xxx × 2k. Because the leading 1 is always the same, it is not stored, and one more bit fits in the fraction field. This is why the 23-bit field gives 24 bits of precision.
The 8086 has no floating-point instruction. Floating-point operations are done either with the 8087 math coprocessor or with software routines written with integer instructions. The 8087 is a separate chip attached next to the 8086 that works on numbers in this format with its own register stack. The 64-bit double-precision format applies the same idea with 1 + 11 + 52 bits; its exponent bias is 1023.
1.2.7.2Decoding
Let us find the value of the pattern 0 01111100 01000000000000000000000, that is, 3E200000h.
- The sign bit is 0: the number is positive, the factor is (+1).
- The exponent field is 0111 1100b = 124. The true exponent is 124 − 127 = −3: the factor is 2−3.
- The fraction field is 0100…0: 0 × 2−1 + 1 × 2−2 = 0.25. With the hidden bit it is 1.25.
- The value is (+1) × 1.25 × 2−3 = 1.25 / 8 = 0.156 25.
The hexadecimal form of the pattern is found by putting the fields together and grouping in fours: 0011 1110 0010 0000 … = 3E200000h.
1.2.7.3Encoding
Let us convert −6.5 to the 32-bit IEEE 754 format.
- The number is negative: the sign bit is 1.
- The magnitude is converted to binary: 6 = 110b, 0.5 = 0.1b; 6.5 = 110.1b.
- It is normalized: the point moves two places left, 110.1b = 1.101b × 2².
- Exponent: 2 + 127 = 129 = 1000 0001b.
- Fraction: the hidden 1 is dropped, and the remaining 101 is padded on the right with 0s to 23 bits: 1010 0000 0000 0000 0000 000.
- The fields are combined: 1 10000001 10100000000000000000000 = 1100 0000 1101 0000 0000 … = C0D00000h.
In 8086 memory this pattern sits, starting from the lowest address, in the order 00 00 D0 C0; the lowest byte is written to the lowest address (little-endian order).
1.2.7.4Special patterns
Two extreme values of the exponent field (0 and 255) are reserved for special meanings. Table 1.2.16 lists them.
| Pattern | Meaning |
|---|---|
| e = 0, f = 0 | ±0 (+0 or −0 according to the sign bit) |
| e = 255, f = 0 | ±∞ (e.g. 1/0) |
| e = 255, f ≠ 0 | NaN, “not a number” (e.g. 0/0) |
| e = 0, f ≠ 0 | denormalized, very small number: 0.f × 2−126 |
Zero cannot be written with the hidden-bit rule; 1.f is always at least 1. That is why a separate pattern is defined for zero. Having a separate sign bit gives rise to +0 and −0; the standard requires them to compare equal. The infinity and NaN values let a computation continue instead of stopping with an error. Denormalized numbers fill the gap in the region near zero. The smallest normalized number is 2−126; values below it are stored without the hidden bit as 0.f × 2−126.
The precision of floating-point numbers is limited. In single precision the 24-bit significand corresponds to about 7 decimal digits. A value like 0.1 that is not finite in binary is rounded to these 24 bits: in single precision the pattern 3DCCCCCDh stands for 0.100 000 001 49…. This small error accumulates when additions are done one after another.
1.2.8Binary-coded decimal (BCD)
The binary system is efficient for computation, but people read decimal. To print a number on the screen it has to be divided by 10 each time to separate its digits; this needs a slow sequence of DIVs. In applications where numbers are displayed often and computed little, another encoding is used: each decimal digit is written separately in binary.
In binary-coded decimal (BCD) encoding each decimal digit is represented with four bits: 0 = 0000, …, 9 = 1001. The patterns 1010 … 1111 are invalid. Packed BCD puts two digits in a byte (25 → 25h); unpacked BCD puts one digit in each byte (25 → 02h 05h).
The difference between BCD and binary is seen in an example. 25 in BCD is 0010 0101: the left nibble shows 2 and the right one 5. The binary equivalent of the same number is 0001 1001 = 19h. In packed BCD the hexadecimal notation of a byte is the same as the digits of the decimal value: BCD 25 = 25h. This property makes BCD numbers very easy to read in a memory dump. The price is inefficient use of space: a byte holds 0 … 255 in binary but only 0 … 99 in packed BCD.
BCD is used where decimal digits are represented directly. The real-time clock (RTC) chip in computers keeps the hour, minute, and date in BCD; 14:35 is stored as the bytes 14h and 35h. Seven-segment displays are driven by decoders that take a BCD digit and light the corresponding segments. Calculators and financial software use BCD arithmetic so that decimal fractions such as 0.1 are stored exactly.
1.2.8.1BCD addition and correction
If two packed BCD numbers are added with a binary adder, the result is not always valid BCD. When the sum of a nibble exceeds 9, the binary adder leaves it between 10 and 15; in the decimal system, however, a digit that reaches 10 should turn into a carry. This difference is fixed with a correction: 6 is added to the invalid digit. The number 6 is the difference between the 16 patterns of a nibble and the 10 values of a decimal digit. Adding 6 skips the six unused patterns (1010 … 1111) and passes the carry to the next nibble up.
Let us add BCD 38 and BCD 45. 38 = 0011 1000, 45 = 0100 0101. The binary sum is 0111 1101 = 7Dh. The low nibble 1101 = 13 is invalid in BCD. 6 is added to this nibble: 7Dh + 06h = 83h = 1000 0011. The result is BCD 83, and 38 + 45 = 83 is correct.
There is a second case that needs correction: the low nibble looks valid but has actually overflowed. In 29 + 18 the binary sum is 29h + 18h = 41h. The low nibble is 1 and looks valid; yet 9 + 8 = 17. A carry has come out of the low nibble into the next one up, taking the value 16 with it. The 8086 keeps this carry in the auxiliary carry flag (AF). If AF = 1, 6 is again added to the low nibble: 41h + 6 = 47h, that is, BCD 47 = 29 + 18. If the high digit exceeds 9 or produces a carry, 6 is added to it too, that is, 60h is added to the byte; in that case CF = 1 and the result has exceeded 99.
The 8086 applies all these rules with a single instruction: DAA (decimal adjust after addition). If DAA is run right after two packed BCD numbers are added with ADD AL, BL, AL is corrected to valid BCD. DAA looks at the low nibble of AL and AF, then the high nibble and CF, and adds 06h, 60h, or 66h. Its counterpart for subtraction is DAS. DAA works only on AL; multi-digit BCD numbers are processed byte by byte, added with carry (ADC) and applying DAA after each byte.
Looking only at “is the nibble greater than 9?” and forgetting AF. In 29h + 18h = 41h the low nibble is 1 and no correction seems needed; but the result should be 47, not 41. Another mistake is to read a BCD number like a hexadecimal number: 47h is 71 in hexadecimal but 47 in BCD. 2Fh is the binary equivalent of decimal 47 and is not BCD.
1.2.9Byte order: little-endian and big-endian
Memory is addressed byte by byte. In what order the bytes of a 16- or 32-bit value are laid out when it is written to memory is a design decision. There are two opposite conventions.
In little-endian order the least significant byte of a multibyte value is written to the lowest address. In big-endian order the most significant byte is written to the lowest address. The 8086 and the whole x86 family are little-endian.
Figure 1.2.39 shows the 32-bit 12345678h in the two orders. In little-endian, 78h is at address 0100h and 12h at address 0103h. When a memory dump is read from left to right, the value looks “reversed.” In big-endian the bytes sit in the order they were written and the dump reads directly. Systems that use big-endian include the Motorola 68000, most PowerPC configurations, and network protocols. Internet protocols transmit multibyte fields in big-endian; this order is called network byte order. An x86 machine must swap the bytes of a 16-bit port number received from the network before using it.
Little-endian has one convenience: the address of a value points to its low byte regardless of the value’s width. To read the low byte of a word at address 0100h, one still looks at address 0100h. On the 8086, the instruction MOV AX, [0100h] loads AL from 0100h and AH from 0101h. From the same address, MOV AL, [0100h] takes only the low byte and finds the low byte of the same value.
Suppose the 32-bit A1B2C3D4h has been written to address DS:0300h with DD 0A1B2C3D4h. In little-endian order the bytes are 0300h: D4h, 0301h: C3h, 0302h: B2h, 0303h: A1h. Now consider the following three instructions. MOV AX, [0302h] takes AL from 0302h (B2h) and AH from 0303h (A1h): AX = A1B2h. MOV BL, [0301h] reads a single byte: BL = C3h. MOV CX, [0301h] takes CL from 0301h (C3h) and CH from 0302h (B2h): CX = B2C3h. The last read is a word read starting at an odd address; the 8086 does it with two separate bus cycles and spends four extra clock cycles.
Thinking little-endian stores the bits in reverse order. The ordering is at the byte level; the bits inside each byte do not change. 1234h is written to memory as 34 12, not as 43 21 or 2C 48. Another mistake is to expect 12h when reading a word defined with DW 1234h using MOV AL, [address]; the low address holds 34h.
1.2.10The Gray code
In ordinary binary counting, more than one bit can change between two consecutive numbers. Going from 3 to 4, 011 → 100, three bits change at once. At the output of a rotary encoder or a counter these bits do not change at exactly the same moment physically. A value read during the transition may be an intermediate value that is neither 3 nor 4, such as 111 (7) or 000 (0). The Gray code solves this problem at the root.
The Gray code is an encoding in which only one bit changes between any two consecutive values. The Gray code of a binary number B is found with the formula G = B XOR (B >> 1).
| Decimal | Binary | Gray | Changed bit |
|---|---|---|---|
| 0 | 000 | 000 | — |
| 1 | 001 | 001 | 1 |
| 2 | 010 | 011 | 2 |
| 3 | 011 | 010 | 1 |
| 4 | 100 | 110 | 3 |
| 5 | 101 | 111 | 1 |
| 6 | 110 | 101 | 2 |
| 7 | 111 | 100 | 1 |
Table 1.2.17 gives the 3-bit sequence: 000, 001, 011, 010, 110, 111, 101, 100. The transition from 3 to 4 is 010 → 110 in Gray code; only the top bit changes, and no wrong intermediate value can be read. The sequence also closes on itself: going from 7 (100) to 0 (000) also changes a single bit. This is why the Gray code is widely used in rotary encoders that measure the angle of a shaft. The same code also appears in some types of analog-to-digital converters and in the row-column ordering of Karnaugh maps. Single-bit changes make the transitions robust against electrical noise and timing differences.
1.2.10.1From binary to Gray code and back
The meaning of the formula is this: the top bit of the Gray code is the same as in binary; each following bit is the XOR of that bit in binary and the bit to its left. B >> 1 brings the bit to the left of each bit into its own position; the XOR compares the two bits. If a bit in the Gray code is 1, then that bit and the bit to its left differ in binary.
Let us find the Gray code for B = 0110 (6). B is shifted right by one bit: B >> 1 = 0011. XOR is taken bit by bit: 0110 ⊕ 0011 = 0101. The Gray code of 6 is 0101. Check by the rule: top bit 0; then 0 ⊕ 1 = 1, 1 ⊕ 1 = 0, 1 ⊕ 0 = 1 → 0101.
Converting from Gray code back to binary goes the other way. The top bit of the binary equals the top bit of the Gray code. Each following bit is the XOR of the binary bit found just before it and the bit in the same position in the Gray code: Bi = Bi+1 ⊕ Gi. For 0101: B3 = 0; B2 = 0 ⊕ 1 = 1; B1 = 1 ⊕ 0 = 1; B0 = 1 ⊕ 1 = 0. The result is 0110 = 6. The conversion back is done not in a single step like the forward direction but with a chain that proceeds bit by bit.
1.2.10.2Code trace: Gray code with SHR and XOR
The formula is written on the 8086 with three instructions: copy the value, shift the copy right by one, and XOR the two values. The following program computes the Gray code of two consecutive numbers, 11 and 12.
ORG 100h
MOV AL, 1011b ; 11
MOV BL, AL
SHR BL, 1 ; B >> 1
XOR BL, AL ; G
MOV AL, 1100b ; 12
MOV BH, AL
SHR BH, 1
XOR BH, AL ; G
RETMOV AL, 1011b loads 11 into AL. MOV BL, AL copies the value into BL; the shift will be done on the copy, and the value B is kept in AL. SHR BL, 1 shifts BL right by one: 0000 1011 → 0000 0101. The rightmost 1 falls into CF and a 0 enters at the far left. XOR BL, AL compares the two values bit by bit: 0101 ⊕ 1011 = 1110. BL = 0Eh, the Gray code of 11. The XOR instruction always sets CF and OF to 0; it sets ZF and SF according to the result. The second half of the program does the same job for 12 on BH: 1100 → SHR → 0110 → XOR → 1010 = 0Ah.
| Instruction | AL | BL | BH | Note |
|---|---|---|---|---|
MOV AL, 1011b | 0Bh | 00h | 00h | B = 11 |
MOV BL, AL | 0Bh | 0Bh | 00h | copy |
SHR BL, 1 | 0Bh | 05h | 00h | 0101b; dropped bit CF = 1 |
XOR BL, AL | 0Bh | 0Eh | 00h | 1011 ⊕ 0101 = 1110: Gray(11) |
MOV AL, 1100b | 0Ch | 0Eh | 00h | B = 12 |
MOV BH, AL | 0Ch | 0Eh | 0Ch | copy |
SHR BH, 1 | 0Ch | 0Eh | 06h | 0110b; dropped bit CF = 0 |
XOR BH, AL | 0Ch | 0Eh | 0Ah | 1100 ⊕ 0110 = 1010: Gray(12) |
The result confirms the basic property of the Gray code. In going from 11 to 12 three bits change in binary: 1011 → 1100. In Gray code only one bit changes: 1110 → 1010. In the program BL and BH are the two halves of the same BX register; when the program ends, BX = 0A0Eh. Because BH and BL can be addressed separately, the two 8-bit results sit side by side in a single 16-bit register.
1.2.11Summary
- In a positional system the value of a number is the sum of each digit multiplied by its place weight, a power of the base: N = Σ di × bi. Roman numerals make arithmetic hard because they have no zero and no place value.
- Computers use the binary system because two-state elements are easy to build. n bits give 2n patterns: a byte 0 … 255, a word 0 … 65,535.
- A hexadecimal digit is exactly one nibble; one moves between binary and hexadecimal by groups of four from the right. In assembly the suffixes
b,h, andoindicate the base; a 0 is put in front of a hexadecimal number that starts with a letter. The base is only a way of writing:65,41h, and'A'produce the same codeB0 41. - The integer part is converted from decimal to another base with the divide-and-remainder method, and the remainders are read from bottom to top. The fractional part is converted with the multiply-by-2 method, and the bits are read from top to bottom. Fractions whose denominator is not a power of 2 (0.1) are not finite in binary.
DIV BXdivides DX:AX, writes the quotient to AX and the remainder to DX; DX must be cleared beforehand.SHRdivides by 2 and drops the remainder into CF;RCRcarries CF into a register.- A bit pattern carries no meaning; the program supplies the interpretation. In two’s complement, −x = NOT x + 1 = 2n − x;
NEGdoes this in one instruction. The MSB is the sign bit; there is a single zero; in 8 bits the range is −128 … +127. One’s complement (NOT) and sign-magnitude have two zeros. - Sign extension copies the sign bit into the upper bits (
CBW,CWD): −5 = FBh = FFFBh. In fixed-point numbers the position of the point is the programmer’s convention; addition is ordinary integer addition. - Binary addition is done with full adders; subtraction is turned into addition of the two’s complement. In hexadecimal a carry arises when a column sum reaches 16; the 15’s and 16’s complement are the counterparts of one’s and two’s complement.
- CF shows that the result did not fit in the unsigned interpretation (carry or borrow), and OF shows that it did not fit in the signed interpretation. OF can be 1 only when numbers of the same sign are added or numbers of different signs are subtracted; the hardware compares the carry into and out of the sign bit.
- Bits in a circuit are voltage levels; threshold ranges provide a noise margin. A flip-flop stores one bit; in the SR type S = R = 1 is forbidden, and in the JK type J = K = 1 toggles. Registers are built from D flip-flops loaded at the rising clock edge.
- An IEEE 754 single-precision number consists of 1 sign bit, 8 exponent bits (bias 127), and 23 fraction bits; the value is (−1)s × 1.f × 2e−127. The 8086 has no floating-point instruction; that job is left to the 8087 or to software.
- BCD holds each decimal digit in four bits; after an addition, 6 is added to an invalid digit or when AF = 1 (
DAA). The 8086 is little-endian: the low byte is at the low address. In the Gray code consecutive values differ in a single bit: G = B ⊕ (B >> 1).
1.2.12Key terms
- positional number system
- base (radix)
- digit
- decimal
- binary
- hexadecimal
- octal
- suffix
- bit
- nibble
- byte
- word
- double word
- MSB / LSB
- signed / unsigned
- sign bit
- sign-magnitude
- one's complement
- two's complement
- sign extension
- fixed-point number
- carry
- borrow
- overflow
- carry flag (CF)
- overflow flag (OF)
- sign flag (SF)
- zero flag (ZF)
- auxiliary carry flag (AF)
- shift
- rotate
- flip-flop
- clock cycle
- floating-point number
- sign / exponent / fraction
- binary-coded decimal (BCD)
- byte order
- Gray code
1.2.13Test Yourself
Write the number 300 in hexadecimal and binary. Does this value fit in AL?
Answer
300 ÷ 16 = 18, remainder 12 (C); 18 ÷ 16 = 1, remainder 2; 1 ÷ 16 = 0, remainder 1. The result is 12Ch; expanding the digits to 4 bits gives 1 0010 1100b. Because the value is greater than 255, it does not fit in the 8-bit AL; nine bits are needed. It fits in AX.
Convert the number 0.3125 to binary. Is the result finite? Why?
Answer
0.3125 × 2 = 0.625 → 0; 0.625 × 2 = 1.25 → 1; 0.25 × 2 = 0.5 → 0; 0.5 × 2 = 1.0 → 1. Reading the bits from top to bottom gives 0.0101b: 1/4 + 1/16 = 0.3125. The result is finite, because 0.3125 = 5/16 and the denominator is a power of 2.
What are the unsigned, two’s complement, and one’s complement interpretations of the pattern 1101 0110b?
Answer
Unsigned: 128 + 64 + 16 + 4 + 2 = 214. Two’s complement: 214 − 256 = −42 (or with the weights −128 + 64 + 16 + 4 + 2 = −42). One’s complement: inverting the bits gives 0010 1001 = 41; the interpretation is −41.
CBWexecutes with AL = 80h. What does AX become? What would have been found had the same value been zero-extended?Answer
The MSB of AL is 1; CBW makes AH = FFh and AX = FF80h. This is −128 in 16 bits (65,536 − 128 = 65,408 = FF80h). Zero extension would have given 0080h = +128; the signed value would not have been preserved.
ADD AL, 1executes with AL = 7Fh. What are AL, CF, OF, SF, and ZF? Interpret the result as unsigned and as signed.Answer
0111 1111 + 1 = 1000 0000, that is, AL = 80h. No carry comes out of the top bit: CF = 0. A carry goes into the sign bit but none comes out: OF = 1. SF = 1, ZF = 0. In the unsigned interpretation 127 + 1 = 128 is correct; in the signed interpretation the result of +127 + 1 appears as −128, which is overflow. It is the 8-bit counterpart of the step from 0111 to 1000 on the number circle.
What value does F4h represent in Q5.3 format?
Answer
F4h = 11110.100b. By the weights, −16 + 8 + 4 + 2 + ½ = −1.5. Shortcut: F4h = 244, as signed 244 − 256 = −12; −12 / 8 = −1.5.
Write the number 0.75 in 32-bit IEEE 754 format.
Answer
0.75 = 0.11b = 1.1b × 2−1. Sign 0; exponent −1 + 127 = 126 = 0111 1110b; fraction 1000…0. The pattern is 0 01111110 10000000000000000000000 = 0011 1111 0100 0000 … = 3F400000h.
AL = 66h and BL = 57h are packed BCD numbers. After
ADD AL, BLand thenDAA, what are AL and CF?Answer
The binary sum is 66h + 57h = BDh. The low nibble D (13) is invalid: adding 6 gives C3h. The high nibble C (12) is also invalid: adding 60h gives 123h. AL = 23h, CF = 1. The result is BCD 123: 66 + 57 = 123; the hundreds digit is in CF.
DW 1234h, 0ABCDhhas been defined starting at DS:0200h. What is AX afterMOV AX, [0201h]?Answer
In little-endian order the bytes are 0200h: 34h, 0201h: 12h, 0202h: CDh, 0203h: ABh. AL is loaded from 0201h (12h) and AH from 0202h (CDh): AX = CD12h. Because the read starts at an odd address, it takes two bus cycles.
What is the binary equivalent of the 4-bit number whose Gray code is 1001? Check the result with the formula.
Answer
B3 = G3 = 1; B2 = 1 ⊕ 0 = 1; B1 = 1 ⊕ 0 = 1; B0 = 1 ⊕ 1 = 0. The binary equivalent is 1110 = 14. Check: 1110 ⊕ 0111 = 1001.
1.2.14Further reading
- M. M. Mano and M. D. Ciletti, Digital Design (5th edition), Chapters 1, 4, and 5: number systems, complements, BCD and the Gray code, and adder circuits and flip-flops, treated in detail from the digital-design point of view.
- B. B. Brey, The Intel Microprocessors (8th edition), Chapter 1: number systems, signed numbers, BCD, and byte order are tied directly to the data formats of the 8086 family.
- D. Goldberg, “What Every Computer Scientist Should Know About Floating-Point Arithmetic,” ACM Computing Surveys, 23(1), 1991: the classic paper explaining IEEE 754’s rounding, special values, and error accumulation.
- D. E. Knuth, The Art of Computer Programming, Vol. 2: Seminumerical Algorithms, Section 4.1: gives the history of positional number systems and the methods of base conversion, with proofs.
1.2.15References
- M. Morris Mano, Michael D. Ciletti, Digital Design, 5th edition, Pearson, 2013.
- Barry B. Brey, The Intel Microprocessors, 8th edition, Pearson, 2009, Chapter 1.
- IEEE Std 754-2019, IEEE Standard for Floating-Point Arithmetic.
- emu8086 documentation, Numbering systems tutorial.
- Mehmet Bodur, Mikroişlemcilere Giriş: Assembler ile Yazılım ve Arayüz, EMO, 2014.
- Şadi Çağatay Öztürk, Oğuz Ergin, Intel 8086 ile Mikroişlemci Programlamaya Giriş, 2009.
- David Goldberg, “What Every Computer Scientist Should Know About Floating-Point Arithmetic”, ACM Computing Surveys, 23(1):5–48, 1991.
- Donald E. Knuth, The Art of Computer Programming, Vol. 2: Seminumerical Algorithms, 3rd edition, Addison-Wesley, 1997.
Related pages: Chapter 1.2 slides · © Sercan Külcü. All rights reserved.