Computer Arithmetic
IntermediateLesson 3 of 6 in Computer Organization and Architecture Course
What you will learn
- Use one binary adder for signed and unsigned addition and subtraction, and decide when a result no longer fits in its bits.
- Add and subtract binary integers with one adderAdd n-bit numbers column by column, subtract by adding the two's complement, and see why the same circuit serves signed and unsigned values.
- Detect overflow for signed and unsigned resultsTell carry from overflow, detect each one with simple hardware or a short instruction sequence, and know what processors and languages do when it happens.
- Add and subtract binary integers with one adder
- Build an ALU from 1-bit slices that adds, subtracts, compares and performs logic operations, and make its carry chain fast.
- Build an n-bit ALU from 1-bit slicesCombine logic gates, a full adder and multiplexers into a 1-bit ALU, chain the slices into an n-bit ALU, and select operations with control lines.
- Compare numbers and detect zero in the ALUProduce the Zero output for equality branches and the less-than result for signed and unsigned comparisons, including the overflow correction.
- Speed up addition with carry lookaheadExplain why carries make ripple adders slow, and compute carries in advance with generate and propagate signals.
- Build an n-bit ALU from 1-bit slices
- Multiply and divide the way hardware does, from simple shift-and-add circuits to signed rules, fast multipliers and the RISC-V instructions.
- Multiply with shift and addMultiply unsigned binary numbers with the sequential shift-and-add algorithm, size the product correctly, and use shifts for powers of two.
- Multiply signed numbers and multiply fastHandle two's complement operands, recode multipliers with Booth's algorithm, and explain how tree multipliers reach high speed.
- Divide integers and handle the special casesDivide with the restoring algorithm, apply the sign rules for quotient and remainder, and know how hardware and RISC-V treat division by zero and overflow.
- Multiply with shift and add
- Encode and decode IEEE 754 binary values, explain the range and precision of each format, and recognize zeros, infinities, NaNs and subnormal numbers.
- Encode and decode IEEE 754 binary formatsWrite a number in normalized binary scientific notation, store it in the sign, biased exponent and fraction fields, and read stored bits back as a value.
- Use zeros, infinities, NaNs and subnormal numbersRecognize the reserved exponent patterns, explain gradual underflow, and predict the results and flags of exceptional operations.
- Encode and decode IEEE 754 binary formats
- Follow the hardware steps of floating-point addition and multiplication, round results correctly, and predict the precision errors that follow.
- Add and multiply floating-point numbersAlign, operate, normalize and round in the order floating-point hardware does, and use the RISC-V floating-point instructions.
- Round results correctlyApply the IEEE 754 rounding directions, round to nearest with ties to even, and use guard, round and sticky bits to round as if with infinite precision.
- Predict and avoid precision errorsExplain why familiar decimal values are inexact in binary, why floating-point addition is not associative, and how absorption, cancellation and conversions cause real failures.
- Add and multiply floating-point numbers
Computer Arithmetic study guide
1Add and subtract integers and detect overflow
An adder produces bits before anyone decides whether those bits represent signed or unsigned numbers. Follow the carries through addition, reuse the same circuit for subtraction, and then test the result against the right range. The distinction matters in software too: a processor may keep status flags, return the low bits, or raise an exception, while a programming language gives those machine operations its own rules.
1.1 Add and subtract binary integers with one adder
A binary adder does the same small job at each bit position. It combines the two operand bits with a carry from the position to the right. The meaning of the completed bit pattern comes afterward.
Follow the carry
A half adder has two inputs: its sum is their XOR and its carry is their AND. A full adder also accepts a carry-in:
Here multiplication means AND and addition means OR. The sum is 1 for an odd number of 1 inputs; the carry is 1 for at least two. Chaining full adders makes a ripple-carry adder. Only bit 0 receives the initial carry; every later bit receives the carry produced by its neighbor.
For 23 + 45, write 0001 0111 + 0010 1101. At bit 0, 1 + 1 produces sum 0 and carry 1. At bit 1, 1 + 0 + 1 again produces 0 and carry 1. At bit 2, three 1 inputs produce sum 1 and carry 1. Continuing left gives 0100 0100, or 68, with no final carry.
An n-bit result keeps only the low n bits, so the circuit computes the sum modulo . In 8 bits, 1111 1100 + 0000 0101 produces 0000 0001 and carry-out 1. Read as signed, this is −4 + 5 = 1. Read as unsigned, it is 252 + 5 = 257, whose low eight bits represent 1. The circuit has not changed; the permitted range has.
Turn subtraction into addition
Two's complement gives the identity
A subtraction control line XORs every bit of the second operand with 1, inverting it, and sets the initial carry-in to 1. For addition, that line is 0, so the second operand passes unchanged and the initial carry is 0.
To compute 23 − 45, invert 0010 1101 to 1101 0010. Add 0001 0111 + 1101 0010 + 1 to obtain 1110 1010, with carry-out 0. Its signed value is −22. Leaving the initial carry at 0 would give −23: inversion alone supplies one less than the required negative value.
For unsigned subtraction, carry-out 1 means no borrow; carry-out 0 means a borrow was needed. Thus the carry-out 0 in 23 − 45 reports an unsigned result below zero. Arm records this no-borrow carry; x86 records its inverse as the borrow flag.
Match widths before operating
| Interpretation | Extension rule | Extending 4-bit 1110 to 8 bits |
|---|---|---|
| Signed two's complement | Copy the sign bit | 1111 1110, still −2 |
| Unsigned | Insert zeros | 0000 1110, still 14 |
RISC-V lb sign-extends a byte, lbu zero-extends it, and addi sign-extends its 12-bit immediate. Choose extension from the operand's meaning before sending the bits to the adder.
The most negative signed value has no positive partner at the same width. Negating 8-bit 1000 0000 inverts it to 0111 1111 and adds 1, returning 1000 0000. The desired +128 needs a wider signed format.
Key Takeaways
- A full adder combines two operand bits and one carry-in.
- The stored n-bit sum is the mathematical sum modulo .
- Subtraction inverts the second operand and sets only the initial carry-in to 1.
- In this subtraction circuit, carry-out 1 means no unsigned borrow.
- Sign extension preserves signed values; zero extension preserves unsigned values.
1.2 Detect overflow for signed and unsigned results
Overflow means the exact result falls outside the destination's range. Unsigned n-bit values run from 0 through ; signed two's complement values run from through . Eight bits hold 0 through 255 unsigned, or −128 through 127 signed. The same stored result can be valid in one reading and overflow in the other.
Test the right signal
| Operation | Unsigned overflow | Signed overflow |
|---|---|---|
| Addition | Carry out of the top bit is 1 | Same-sign inputs produce a result of the opposite sign |
| Subtraction | A borrow is needed | Different-sign inputs produce a result whose sign differs from the first input |
For signed addition or subtraction, hardware can use
where the two carries enter and leave the sign position. Carry-out alone answers the unsigned question.
Add 107 and 54 in 8 bits: 0110 1011 + 0011 0110 gives 1010 0001. A carry enters bit 7 but none leaves, so overflow is 1. The unsigned value 161 fits; the signed reading −95 does not equal the true sum 161. Conversely, −4 + 5 gives carry 1 but signed overflow 0. Adding 1000 0000 to itself gives carry 1 and overflow 1, so both readings fail.
Adding opposite signs cannot overflow: the exact sum lies between the operands. Subtraction needs its own sign rule because subtracting a negative increases the first operand. For example, 100 − (−40) is too large for signed 8 bits even though both input values fit.
Know what the instruction does
x86 add sets carry and overflow flags. Arm flag-setting operations such as ADDS set them; ordinary ADD preserves the existing flags. MIPS add and addi trap on signed overflow, while addu and addiu do not. RISC-V integer addition writes the low bits and has no overflow flags or arithmetic-overflow trap.
After add t0, t1, t2, an unsigned RISC-V check is:
bltu t0, t1, overflow
A wrapped unsigned sum is smaller than an original operand. Signed values need a different check:
slti t3, t2, 0
slt t4, t0, t1
bne t3, t4, overflow
The first instruction records whether the second operand is negative. The second records whether the result is smaller than the first operand. Without overflow these tests agree: adding a negative decreases the value, while adding a nonnegative value cannot decrease it. A mismatch detects overflow. For a known positive immediate, a signed branch testing whether the sum decreased is enough.
Separate hardware from language rules
C and C++ unsigned arithmetic wraps modulo ; signed overflow is undefined behavior. Java int and long wrap, while Math.addExact reports overflow with an exception. Python integers grow as needed. A hardware wrap therefore does not establish what a C program is allowed to do.
Wrapping additions and subtractions preserve a final result that fits: in 8-bit modular arithmetic, (100 + 50) − 60 wraps first to −106 and then to 90. This reasoning applies to wrapping arithmetic, not C signed expressions that overflow.
Saturation is a different policy. Unsigned 8-bit 200 + 100 saturates to 255 instead of wrapping to 44. It is useful for pixel intensities and other bounded signals, where wrapping a large positive result to a small value would be misleading.
Key Takeaways
- Choose overflow tests from the operand interpretation and operation.
- Signed overflow is the XOR of the carries into and out of the sign bit.
- RISC-V software must test for integer overflow when it needs to report it.
- C signed overflow, Java wrapping, and growing Python integers have different semantics.
- Modular addition and subtraction can recover a representable final value after intermediate wrapping.
- Saturation clamps an out-of-range result to an endpoint.
2Design an arithmetic logic unit
An ALU turns a choice of operations into one shared circuit. Gates and an adder compute candidate results, control lines select one, and a few extra outputs support equality and ordering. Build that structure from bit slices, see why signed comparison needs overflow correction, and then shorten the carry path so a wider datapath can produce its arithmetic result without waiting for a carry to cross every bit.
2.1 Build an n-bit ALU from 1-bit slices
An arithmetic logic unit, or ALU, takes operands and control inputs and produces a result plus status outputs. It is combinational: its outputs depend on the present inputs. Registers hold operands and capture results; the ALU itself stores nothing.
Build one bit, then repeat it
A 1-bit slice computes AND, OR, and a full-adder sum in parallel. A multiplexer selects which candidate reaches the result bit. In an n-bit ALU, all slices share the operation controls, while each adder's carry-out feeds the next slice's carry-in. Logic operations work independently at each position; addition depends on the carry chain.
A Bnegate control both inverts the second operand and sets the carry-in of bit 0. Selecting the adder then computes subtraction. Higher slices take their carry from the preceding slice, not directly from Bnegate. Driving every carry input high would insert extra ones into the calculation.
An Ainvert control can also invert the first operand. Selecting AND with both operands inverted produces NOR by De Morgan's law:
Selecting OR with both inverted produces NAND. In these logic equations, the plus sign denotes OR.
Read a control word
One classic textbook ALU uses the fields Ainvert, Bnegate, and a two-bit Operation selector:
| Control word | Selected result |
|---|---|
0000 | AND |
0001 | OR |
0010 | Add |
0110 | Subtract |
0111 | Signed set on less than |
1100 | NOR |
These are the encodings of this particular design. They are internal controls, not RISC-V instruction encodings.
For inputs 0101 and 0011, control 0110 inverts the second input to 1100 and supplies initial carry 1. The adder produces 0010, with carry-out 1: 5 − 3 = 2, with no unsigned borrow. Selecting AND for the original inputs would instead produce 0001. The input values can stay fixed while a control change selects a different result path.
The most significant slice also supplies overflow and comparison information. A reduction of all result bits supplies Zero. Those status outputs let the surrounding processor control test the arithmetic result without storing a second full-width result.
Add shifting beside the adder
A full RISC-V base-integer ALU also needs XOR, unsigned comparison, and shifts. A barrel shifter uses a sequence of multiplexer levels. Each level either passes its input through or shifts by a power of two. A 32-bit shifter has levels for 1, 2, 4, 8, and 16 positions, so it handles any shift from 0 through 31 in five levels.
To shift by 13, select the levels for 8, 4, and 1. The selected shifts compose into one result. A logical right shift inserts zeros. An arithmetic right shift replicates the sign bit, preserving a negative value's sign. Thus 1111 0000 shifted right by two gives 0011 1100 logically and 1111 1100 arithmetically.
Key Takeaways
- An ALU computes from current inputs; registers provide storage.
- Bit slices share operation controls and pass carries between adjacent positions.
- Bnegate inverts the second operand and supplies the initial carry for subtraction.
- A multiplexer selects among arithmetic and logic results.
- Barrel-shifter levels combine shifts by powers of two.
2.2 Compare numbers and detect zero in the ALU
Comparisons often reuse subtraction. Equality asks whether the difference is zero. Ordering asks whether the mathematical difference is negative, which needs extra care when a fixed-width subtraction overflows.
Detect equality across every bit
The Zero output is the NOR of all result bits:
One nonzero result bit makes Zero false. Subtracting two equal bit patterns produces zero; two distinct n-bit patterns cannot differ by a nonzero multiple of , so wrapped subtraction does not create a false equality. An alternative equality circuit XORs corresponding operand bits and tests whether every XOR result is zero.
Correct the sign for signed less-than
RISC-V slt writes the full-width integer 1 if the first signed operand is smaller, or 0 otherwise. In a sliced ALU, the most significant slice computes a Set signal and sends it back to bit 0's Less input. All higher result bits are forced to zero.
The correct Set signal is
When there is no overflow, the sign of the difference works directly. When there is overflow, that sign is reversed relative to the true difference, so XOR with 1 corrects it.
Compare 7 with −8 in four bits. The subtraction 0111 + 0111 + 1 gives 1111. Its sign suggests a negative difference, but the exact difference is 15, outside the range −8 through 7. Overflow is 1, so the corrected Less signal is 1 XOR 1 = 0. The slt result is 0000, correctly reporting that 7 is not smaller than −8.
Use borrow for unsigned less-than
Unsigned comparison uses a different signal:
for subtraction performed with inverted second input and initial carry 1. Carry-out 0 means a borrow was needed, so the first unsigned operand is smaller.
| Input patterns | Signed comparison | Unsigned comparison |
|---|---|---|
0111, 1000 | 7 < −8 is false | 7 < 8 is true |
1000, 0111 | −8 < 7 is true | 8 < 7 is false |
This distinction appears in slt versus sltu, and in the branches blt versus bltu and bge versus bgeu. Neither the result's sign alone nor a generic “negative flag” answers both questions.
Apply the comparison in software
An unsigned bounds check can reject negative indices as well as indices at or above the array length:
bgeu x10, x11, IndexOutOfBounds
Here x10 holds the signed index and x11 holds a nonnegative length that fits in the signed range. A negative index, reinterpreted as unsigned, is at least and therefore exceeds every such length. The length condition matters: it makes one unsigned comparison sufficient.
Language conversions can change comparison meaning too. With a 32-bit C unsigned int, -1 < 0u is false because −1 converts to 4,294,967,295 before comparison. Trace the conversion before reasoning from the written minus sign.
Key Takeaways
- Zero tests every result bit, so subtraction can implement equality.
- Signed less-than uses the difference's sign XOR signed overflow.
- Unsigned less-than uses the borrow from subtraction.
- Set-on-less-than writes 0 or 1 across the full result width.
- An unsigned bounds check catches negative indices when the length fits the nonnegative signed range.
- Conversions can change a comparison from signed to unsigned.
2.3 Speed up addition with carry lookahead
A ripple adder's carry has to cross each bit in order. Carry lookahead replaces that serial wait with logic that predicts carries from operand bits and the initial carry.
Describe each bit's carry behavior
Let generate and propagate be
These are Boolean expressions: multiplication is AND and addition is OR. Generate is 1 when the bit creates a carry regardless of the incoming carry. Propagate is 1 when an incoming carry can pass through. The recurrence is
A bit with both inputs 1 generates a carry; a bit with one input 1 passes a carry; a bit with both inputs 0 stops it. With this OR definition, a generating bit also has propagate 1, which does not change the carry formula.
Expand the dependency
Substitute the expression for each previous carry:
Each expression now depends on operand-derived signals and the initial carry, not a serial chain of intermediate carry outputs. Once the carries are available, each sum bit is still the XOR of its two inputs and carry-in.
For 1011 + 0110 with initial carry 0, generate from bit 0 upward is 0, 1, 0, 0 and propagate is 1, 1, 1, 1. Thus the carries into bits 1 through 4 are 0, 1, 1, 1. The four result bits are 0001 with carry-out 1, representing 11 + 6 = 17.
Build groups instead of giant gates
A four-bit block has group signals
Its output carry is . A second lookahead level combines these block signals using the same rule. Four four-bit blocks and a group-lookahead unit make a 16-bit adder. Further grouping supports wider designs; parallel-prefix adders such as Kogge–Stone organize these relationships into a fast network.
In a simple gate-delay model, a ripple carry costs about two gate delays per bit, or 32 for 16 bits. A two-level lookahead design can deliver the last carry in about five: one for bit signals, two for group signals, and two for the group carry. This estimate counts logic levels and assumes the required gates; actual delay also depends on gate size and wiring. Grouping trades more hardware for a carry path that grows roughly logarithmically with width.
A carry-select adder spends area differently: it calculates an upper block twice, once for carry-in 0 and once for carry-in 1. A multiplexer selects the correct result when the lower block's carry arrives.
Some adders define propagate with XOR instead of OR. That also gives correct carries, and makes the sum . Keep the chosen definition consistent when deriving group logic.
Key Takeaways
- Generate creates a carry; propagate passes an incoming carry.
- Expanding carry equations removes serial dependence on each preceding carry output.
- Group generate and propagate let wide adders use several lookahead levels.
- Lookahead and carry-select trade circuit area for speed without changing the sum.
3Multiply and divide integers in hardware
Multiplication combines shifted partial products; division decides one quotient digit from a changing remainder. Trace both processes in small registers, then see how signed operands change the bookkeeping. Faster multipliers form and reduce many partial products together, while dividers must manage dependencies between steps. RISC-V instructions expose product halves, quotients, and remainders with precise rules for exceptional inputs.
3.1 Multiply with shift and add
Each binary multiplier bit chooses a shifted copy of the multiplicand or zero. Adding those partial products gives the result. An n-bit operand times an m-bit operand can require n + m bits, so two 32-bit operands need a 64-bit full product.
Trace shift-and-add
For n-bit unsigned operands, initialize a 2n-bit product to zero. Repeat n times: test the multiplier's low bit, add the current multiplicand if that bit is 1, shift the multiplicand left, and shift the multiplier right. The multiplicand register must be wide enough to retain its shifted copies.
For four-bit 6 × 5, the multiplier is 0101:
| Step | Multiplier low bit | Shifted multiplicand | Running product |
|---|---|---|---|
| 1 | 1 | 0000 0110 | 0000 0110 |
| 2 | 0 | 0000 1100 | 0000 0110 |
| 3 | 1 | 0001 1000 | 0001 1110 |
| 4 | 0 | 0011 0000 | 0001 1110 |
The final product is 30. The bit being tested and the shift direction work together: testing the high bit while shifting the multiplier right would pair bits with the wrong weights. This sequential design takes n steps, including steps whose multiplier bit is zero.
Share register space
The first design uses a 2n-bit multiplicand register and adder. A refined design keeps the multiplicand fixed in n bits, puts the multiplier in the low half of a 2n-bit product register, and starts the high half at zero.
When the low bit is 1, add the multiplicand into the high half. Keep the adder's carry-out in one extra bit, then shift that carry and both product halves right together. The multiplier bits leave from the right as product bits occupy the space they free. Dropping the carry breaks large products: with four-bit operands, 15 × 15 would incorrectly become 1 instead of 225. At one step per clock, the simple 32-bit implementation takes about 32 cycles.
Keep the product width in view
An unsigned product fits in n bits exactly when its full product's upper n bits are zero. For 6 × 5, the full result is 0001 1110; storing only 1110 gives 14. The multiplication itself was correct, but the narrow destination discarded part of it.
A left shift by k multiplies by when the result fits. Multiplication by 8 becomes a shift by three; multiplication by 10 can use two shifted copies:
(x << 3) + (x << 1)
The arithmetic is . Width and programming-language rules still apply to the shifts and addition; this rewrite does not create more result bits.
Read the RISC-V result halves
mul returns the low XLEN bits, where XLEN is the integer register width. mulhu returns the high half for unsigned operands. The signed high-half instructions are mulh for two signed operands and mulhsu for a signed first operand and unsigned second operand.
Software requesting the full product can issue the appropriate high-half instruction followed by mul with the same operands. An implementation may fuse the pair. The low result alone cannot establish that an unsigned product fits; the upper half supplies that evidence.
Key Takeaways
- Each multiplier bit selects one shifted partial product or zero.
- The full product can require the sum of the operand widths.
- Sequential shift-and-add takes one step per multiplier bit.
- The compact multiplier must preserve the addition carry before shifting.
- An unsigned narrow product fits exactly when its upper half is zero.
- RISC-V provides one low-half and three interpretation-specific high-half multiply instructions.
3.2 Multiply signed numbers and multiply fast
Signed multiplication must handle the operand signs without losing the most negative value. Faster hardware also needs a way to reduce many partial products without waiting for a full carry-propagating addition each time.
Multiply magnitudes safely
One approach records the signs, forms unsigned n-bit magnitudes, multiplies them into 2n bits, and negates the full product if exactly one operand was negative. For four-bit −8, the magnitude bits 1000 represent unsigned 8. They cannot be read as a positive four-bit signed value.
The low n product bits are identical for signed and unsigned interpretations. 1111 × 0010 gives unsigned 30 (0001 1110) or signed −2 (1111 1110). Both low halves are 1110; only the upper halves differ. This is why one mul instruction serves both interpretations.
Follow Booth's decisions
Booth's algorithm works directly with two's complement. Give the accumulator n + 1 bits and sign-extend the multiplicand to that width, so both it and its negative fit. Initialize the accumulator to zero, place the multiplier in its n-bit register, and append one extra bit initialized to zero.
Examine the multiplier's low bit and the appended bit as a pair:
| Pair | Accumulator operation |
|---|---|
10 | Subtract the multiplicand |
01 | Add the multiplicand |
00 or 11 | Leave it unchanged |
After each decision, shift the entire accumulator–multiplier–extra-bit register right arithmetically. Repeat n times; discard the appended bit and the accumulator's redundant top sign bit to obtain the 2n-bit product.
For 2 × (−3), use multiplicand 00010, multiplier 1101, and accumulator 00000. The pairs are 10, 01, 10, 11. After the respective operations and shifts, accumulator and multiplier are 11111 0110, 00000 1011, 11111 0101, and 11111 1010. The low eight product bits 1111 1010 represent −6.
A logical shift would insert zero at the top and corrupt negative partial results. The extra accumulator bit also matters: subtracting a most-negative n-bit multiplicand needs a positive value unavailable in n signed bits.
Reduce the work and the carry paths
Booth recoding replaces a run of 1s with a subtraction at its low end and addition above its high end. For example, 126 is 128 − 2. Alternating bits may offer no saving. Radix-4 Booth examines two multiplier bits per step and uses digits from −2 through +2, reducing the number of partial products.
A fast multiplier forms partial products in parallel. A carry-save adder compresses three words into two without propagating carries across the word. Wallace or Dadda trees repeat that reduction, then use one final carry-propagating adder. Reducing 32 rows to two takes eight carry-save levels. Pipelining allows several products to be in flight; accepting one every cycle does not mean each finishes in one cycle.
For a signed result narrowed to n bits, every upper-half bit must equal the low half's sign bit. Four-bit −8 × −1 gives full product 0000 1000. The upper half is zero but the retained sign bit is 1, so +8 does not fit the signed destination.
Key Takeaways
- Unsigned magnitudes preserve the magnitude of the most negative signed operand.
- Signed and unsigned products share their low half but can have different upper halves.
- Booth uses an extra accumulator bit, paired-bit decisions, and arithmetic right shifts.
- Runs of 1s can be replaced by two Booth operations; alternating patterns may not save work.
- Carry-save trees reduce many partial products before one final carry-propagating addition.
- Pipelining separates result latency from the rate at which new products can start.
- A signed narrow product fits when the upper half is the sign extension of the low half.
3.3 Divide integers and handle the special cases
Division produces a quotient and remainder linked by
For a nonzero unsigned divisor, the remainder is nonnegative and smaller than the divisor. An n-bit dividend and divisor need an n-bit quotient and remainder.
Produce the quotient one bit at a time
Read dividend bits from the most significant end. Double the partial remainder, bring in the next bit, and test whether the divisor fits. Subtract it and write quotient bit 1 if it does; otherwise keep the partial remainder and write 0.
For 0111 divided by 0010, the brought-down partial remainders are 0, 1, 3, and 3. The first two are smaller than 2, so their quotient bits are 0. Each 3 permits a subtraction, leaving remainder 1 and quotient bit 1. The quotient is 0011 and the remainder 0001: 3 × 2 + 1 = 7.
Restoring division tries subtraction first. If the trial result is negative, add the divisor back and write 0; otherwise keep it and write 1. Detect failure with a borrow or an n + 1-bit signed difference. An n-bit sign test is unsafe: four-bit 0 − 9 wraps to 0111, whose top bit is 0 despite the borrow.
Compact hardware puts the dividend in the low half of a 2n-bit register and partial remainder in the high half. It shifts left each step and inserts quotient bits on the right. At completion the high half holds the remainder and the low half the quotient.
Nonrestoring division carries a negative trial result forward and adds the divisor during the next step instead of restoring immediately. A final negative partial remainder needs one last add-back. SRT division selects several quotient bits per step using leading divisor and remainder bits; missing entries in such a selection table caused the 1994 Pentium FDIV bug. Division remains dependent on each preceding partial remainder.
Apply truncating signed division
Divide magnitudes, negate the quotient if signs differ, and give a nonzero remainder the dividend's sign.
| Calculation | Quotient | Remainder |
|---|---|---|
| −7 divided by 2 | −3 | −1 |
| 7 divided by −2 | −3 | 1 |
| −7 divided by −2 | 3 | −1 |
These results truncate the quotient toward zero and preserve the division identity. RISC-V, Java, and C since C99 use this rule. Python // rounds down instead: -7 // 2 is −4 and -7 % 2 is 1.
Handle exceptional inputs
RISC-V division by zero returns an all-ones quotient and the original dividend as remainder. The signed overflow case, most-negative divided by −1, returns the most-negative quotient and remainder zero. Neither case traps. x86 raises a divide-error exception for both. Software that must report errors checks zero first and also checks the signed overflow pair.
A logical right shift divides unsigned values by powers of two, rounding down. An arithmetic shift rounds negative values down too: −5 shifted right by one becomes −3, while truncating division by 2 gives −2. To implement truncation with a shift, add to a negative input before shifting right by k. For −5 and k = 1, shift −4 to obtain −2.
Key Takeaways
- Quotient and remainder must satisfy the division identity.
- Restoring division adds the divisor back after a failed trial subtraction.
- Borrow or an extra difference bit is needed to test unsigned trial subtraction safely.
- Truncating signed division gives a nonzero remainder the dividend's sign.
- RISC-V defines nontrapping outputs for division by zero and signed quotient overflow.
- Arithmetic right shift and truncating signed division differ for negative values with a remainder.
4Represent real numbers in IEEE 754 floating point
Floating point stores a sign, a scale, and a limited set of significant bits. Decode those fields to distinguish range from precision, then use the reserved exponent patterns to recognize zeros, subnormals, infinities, and NaNs. The special values are part of the arithmetic system: they let tiny results approach zero gradually and let exceptional operations return defined results while recording status flags.
4.1 Encode and decode IEEE 754 binary formats
A normal binary floating-point value has the form
The significand is the full value 1.f; the stored fraction contains only f. Normalization guarantees the leading 1, so omitting this hidden bit gains one bit of precision.
Read the three fields
| Format | Sign bits | Exponent bits | Fraction bits | Bias | Precision |
|---|---|---|---|---|---|
| binary16 | 1 | 5 | 10 | 15 | 11 bits |
| binary32 | 1 | 8 | 23 | 127 | 24 bits |
| binary64 | 1 | 11 | 52 | 1023 | 53 bits |
IEEE 754-2019 defines these formats. Single and double precision usually mean binary32 and binary64. The stored order is sign, exponent, fraction. For a normal value, subtract the bias from the unsigned exponent field:
Fraction means the binary fraction after the point, not its bits read as an integer. In binary32, exponent fields 1 through 254 encode exponents −126 through 127. Fields 0 and 255 have special meanings.
A bias makes larger exponents have larger unsigned fields. For positive finite numbers, unsigned ordering of the complete patterns follows numerical ordering. Negative values and NaNs require additional handling.
Encode and decode
To encode −0.75, write its magnitude as . The sign is 1 and the exponent field is −1 + 127 = 126, or 01111110. Drop the hidden leading 1 and pad the fraction with zeros. The fields are 1 01111110 10000000000000000000000, giving 0xBF400000. In binary64 the same value is 0xBFE8000000000000.
To decode 0x41460000, split it into 0 10000010 10001100000000000000000. The exponent field is 130, so the true exponent is 3. The significand is
Multiplying by 8 gives 12.375. Writing the hidden 1 into the stored fraction would change the value; storing −1 directly in the exponent field would lose the bias rule.
Distinguish range from precision
binary32 reaches approximately , with smallest positive normal and about seven significant decimal digits. binary64 reaches approximately , with smallest positive normal and about 15–16 significant digits. binary16 has maximum 65,504, smallest positive normal , smallest positive subnormal , and about 3.3 significant decimal digits.
Precision counts significant digits, not digits after the decimal point. For example, binary32 stores 1,234,567.89 as 1,234,567.875.
Within the binary32 interval from up to , adjacent normal values are spaced apart. This spacing is an ulp, a unit in the last place. Just above 1 it is , often called machine epsilon. At the spacing becomes 2, so 16,777,217 is missing even though much larger numbers fit. More exponent bits widen the scale range; more fraction bits place representable values closer together at a given scale.
Key Takeaways
- Normal formats omit the guaranteed leading 1 from the stored fraction.
- Decode a normal exponent by subtracting its bias.
- binary16, binary32, and binary64 have 11-, 24-, and 53-bit precision.
- Range and precision are different limits.
- Normal-number spacing grows with the exponent.
4.2 Use zeros, infinities, NaNs and subnormal numbers
Reserved exponent patterns let IEEE 754 represent values beyond ordinary normalized numbers. Always classify the fields before applying a value formula.
Recognize the reserved patterns
| Exponent field | Fraction field | Meaning |
|---|---|---|
| All zeros | Zero | Signed zero |
| All zeros | Nonzero | Subnormal |
| All ones | Zero | Signed infinity |
| All ones | Nonzero | NaN |
binary32 has +0 at 0x00000000 and −0 at 0x80000000. They compare equal, but division can reveal the sign: 1 divided by +0 gives +∞, while 1 divided by −0 gives −∞. A tiny negative result that rounds to zero becomes −0.
Positive infinity is 0x7F800000; the largest finite positive value is 0x7F7FFFFF. Under round to nearest, arithmetic overflow returns a signed infinity. Dividing a finite nonzero value by zero also returns signed infinity, with a different exception flag. Later arithmetic handles infinity consistently: adding 1 to +∞ leaves +∞, multiplying it by −2 gives −∞, and its reciprocal is +0.
Distinguish NaN from infinity
Operations such as zero divided by zero, infinity minus itself, zero times infinity, and the real square root of −1 have no meaningful numerical result. They produce NaN, “Not a Number,” and signal invalid operation.
NaN is unordered: equality and ordered less-than or greater-than tests involving it are false, while inequality is true. In particular, x == NaN cannot detect NaN. Use isnan(x). Quiet NaNs normally propagate through arithmetic; signaling NaNs raise invalid when consumed. In these binary formats the top fraction bit distinguishes a quiet NaN. RISC-V's canonical binary32 quiet NaN is 0x7FC00000.
Approach zero gradually
A subnormal has no hidden 1. Its exponent is fixed at the smallest normal exponent:
For binary32, 0x00000001 is and 0x00400000 is . For binary64 the smallest positive value is . Using exponent minus bias with a zero exponent field would be off by a factor of two, even before a mistaken hidden 1 was added.
Subnormals provide gradual underflow: precision decreases as values shrink, with fixed absolute spacing near zero. Distinct finite values in one format still have a nonzero representable difference. Flush-to-zero modes discard that protection and can speed up subnormal handling on some processors.
Read the exception flags
IEEE 754 defines invalid operation, division by zero, overflow, underflow, and inexact. Default handling returns a result and records status; it need not stop execution. Inexact means the rounded result differs from the exact result.
Under default handling, underflow requires both tininess and inexactness. In binary32, is an exact subnormal and does not raise underflow. RISC-V records NV, DZ, OF, UF, and NX in fflags within fcsr, and floating-point exceptions do not trigger arithmetic traps. A returned infinity alone does not identify whether overflow or division by zero occurred; inspect the flag.
Key Takeaways
- Classify reserved exponent fields before decoding a normal value.
- Signed zeros compare equal but can produce differently signed infinities.
- NaN is unordered and must be detected with a NaN test.
- Subnormals use a leading 0 and exponent one minus the bias.
- Gradual underflow preserves small differences that flushing to zero can erase.
- An exact subnormal does not raise the underflow flag.
5Compute and round with floating-point numbers
Floating-point hardware must move and combine significant bits before it can round the answer. Work through alignment, normalization, and rounding, then connect those steps to familiar precision failures. Extra rounding bits distinguish a tie from a value just above it, and fused multiply-add preserves information that two separate operations can lose. The same limits explain changing sums, stalled counters, and risky conversions.
5.1 Add and multiply floating-point numbers
Floating-point arithmetic works on significands and exponents separately. The final result must be the exact operation rounded to the destination format, so intermediate bit movement must preserve enough information for that last decision.
Add with a shared exponent
Addition follows four stages: align, operate, normalize, round. Compare exponents and shift the smaller operand's significand right by their difference. Add magnitudes for equal signs; subtract magnitudes for opposite signs. Shift the result into normalized form and adjust its exponent. Then round, renormalizing again if rounding creates a carry.
Use four-bit significands to see 0.5 + (−0.4375):
- Write the operands as and .
- Align the second to .
- Subtract the magnitudes: .
- Normalize to , or 0.0625. No nonzero bits were lost, so no rounding change is needed.
Cancellation can require a large left-normalizing shift. Hardware uses an exponent subtractor, an alignment shifter, a significand adder, a leading-zero counter, and normalization and rounding logic. Floating-point adders are commonly pipelined across several cycles.
A decimal model shows why extra digits matter: with four significant digits, 99.99 + 0.161 aligns as at scale . The exact intermediate is 10.01510 at that scale. Normalize to and round to . Cutting off the aligned addend too early would lose information needed to choose 100.2.
Multiply scales and significands
Multiply the significands, add the true exponents, and XOR the signs. With biased fields, subtract the bias once:
before normalization adjustments. Two normal significands multiply to a value from 1 up to 4, so their product needs at most one right-normalizing shift. Rounding can require a further adjustment; exponent limits also need checking.
For 0.5 × (−0.4375), binary32 exponent fields give 126 + 125 − 127 = 124, or true exponent −3. The significand product is . Sign XOR is 1, giving .
Round once with fused multiply-add
FMA computes a × b + c with one rounding after the full expression. Separate multiplication and addition round twice. In binary32, take , , and c = −1. Their exact product is . A separate multiply rounds this to 1, so the addition returns zero. FMA retains the small product difference and returns .
RISC-V F supplies 32 floating-point registers, f0 through f31; D widens the same bank for double precision. flw/fsw and fld/fsd transfer values. Arithmetic includes fadd.s, fmul.s, fdiv.s, and fsqrt.s, with .d forms for double precision. fmadd.s computes fused multiply-add. Comparisons such as flt.s write 0 or 1 to an integer register, and fcvt converts formats or integer values.
Key Takeaways
- Addition aligns exponents before combining significands.
- Normalization changes both the significand position and the exponent.
- Multiplying biased exponent fields requires subtracting one bias.
- Rounding can require a second normalization.
- FMA rounds the complete product-plus-sum once.
- RISC-V F and D arithmetic uses a floating-point register bank; comparisons return integer truth values.
5.2 Round results correctly
A finite format cannot store every exact result. Correct rounding means choosing the representable result required by the rounding direction, as if the operation had first been computed exactly. Basic arithmetic, square root, and FMA obey this rule. NaN payload and sign bits need not be identical across processors.
Choose a rounding direction
| Direction | Rule |
|---|---|
| roundTiesToEven | Nearest value; an exact tie chooses a final significand bit of 0 |
| roundTowardPositive | Toward +∞ |
| roundTowardNegative | Toward −∞ |
| roundTowardZero | Toward zero |
| roundTiesToAway | Nearest value; an exact tie goes away from zero |
The first four are required for binary implementations; ties to even is the default. Ties away is required for decimal formats, and RISC-V also supplies it for binary operations. Its names are RNE, RUP, RDN, RTZ, and RMM; an instruction can select a mode directly or use the dynamic mode in fcsr.
For ties to even rounded to whole numbers, 2.5 becomes 2 and 3.5 becomes 4. In binary with four-bit significands, rounds to , and also rounds to . The even bit belongs to the retained significand, not the exponent or a printed decimal digit.
Keep guard, round, and sticky information
After normalization, keep two additional bits beyond the destination significand: guard and round. The sticky bit is the OR of every later discarded bit. It records whether that entire tail is zero.
For nearest rounding, guard 0 means below halfway. Guard 1 with round or sticky 1 means above halfway. Guard 1 with both later indicators 0 means an exact tie. At a tie, increment the retained significand only if its current low bit is 1.
For a four-bit-significand sum of 8 + 0.5625, alignment gives
Retain 1.000; guard is 1, round is 0, and sticky is 1 because the remaining tail contains a 1. The value is above halfway, so increment to . Discarding sticky would falsely make this a tie and choose 8.
A sticky bit is evidence about all lost bits, not simply the third bit after the retained portion. During shifting, once any lost bit is 1, the sticky state stays 1 for that accumulated tail.
Interpret error and overflow
For finite results within range, nearest rounding has absolute error at most half an ulp; directed rounding has error below one ulp. For normal binary32 results, the usual nearest-rounding relative bound is ; for binary64 it is . Subnormal results need absolute-error reasoning because their relative precision declines.
Rounding direction also controls overflow results. Positive overflow gives +∞ under nearest or toward-positive rounding, but the largest finite positive value under toward-zero or toward-negative rounding. Negative overflow gives the mirrored behavior.
Integer conversions have their own rules. In C, representable casts such as (int)2.7 and (int)-2.7 truncate to 2 and −2, independently of the current floating-point rounding direction. Check destination range as well as the discarded fractional part.
Key Takeaways
- Correct rounding chooses the destination value from the exact result and rounding direction.
- An exact nearest-rounding tie chooses the neighbor whose retained low bit is 0.
- Guard and round preserve two extra bits; sticky records any nonzero tail beyond them.
- A nonzero sticky bit can distinguish an above-half result from a tie.
- Rounding direction controls whether overflow returns infinity or a finite endpoint.
5.3 Predict and avoid precision errors
Floating-point errors often follow directly from finite spacing. Separate the error already present in stored operands from the rounding performed by an operation and from information lost during conversion.
Identify representation error
A reduced fraction has a finite binary expansion exactly when its denominator is a power of two. Values such as 0.5, 0.25, and 0.375 are exact. The expansion of 0.1 repeats, so binary32 stores 0x3DCCCCCD, about 0.10000000149011612. binary64 also stores an approximation.
Consequently, binary64 0.1 + 0.2 produces 0.30000000000000004, different from the stored value nearest 0.3. A short printed result such as 0.1 can be the shortest decimal that round-trips to the same stored bits; it does not establish exactness.
For approximate finite results, use a problem-chosen tolerance, for example
The absolute tolerance handles values near zero; relative tolerance scales with magnitude. The tolerances should reflect the calculation and acceptable error, not just the number of digits printed.
Watch addition lose a small input
Absorption occurs under nearest rounding when a small addend cannot move a large operand to its next representable neighbor. In binary32, 16,777,216 + 1 rounds back to 16,777,216: the neighboring values are two apart, and this tie selects the even significand. A float counter adding 1 can therefore stop progressing.
Changing addition order can change the answer. With binary32 x = −1.5 × 10³⁸, y = 1.5 × 10³⁸, and z = 1, (x + y) + z gives 1. But y + z rounds to y, so x + (y + z) gives zero. Addition is not associative. Parallel reductions may change their grouping when the thread count changes, affecting the final bits.
Repeated rounding also accumulates: adding binary32 0.1 ten million times into a binary32 total gives 1,087,937 instead of 1,000,000. A wider accumulator reduces rounding loss. Adding smaller magnitudes together first can also preserve contributions that a large running total would absorb.
Separate cancellation from inexact subtraction
Cancellation removes shared leading digits from nearly equal operands. The subtraction itself can be exact while earlier operand errors become large relative to the small answer. In binary32, 1.0000001 is stored as . Subtracting 1 gives about instead of , roughly 19% relative error.
Check conversions and format choices
binary64 exactly represents every 32-bit integer. binary32 does not: 16,777,217 rounds to 16,777,216 under ties to even. Above , binary64 also misses some integers. Converting a floating-point value to a smaller integer type can exceed its range entirely.
In Ariane 5's 1996 first flight, an out-of-range conversion from 64-bit floating point to a 16-bit signed integer shut down the inertial reference systems and contributed to the loss of the rocket. In the 1991 Patriot failure at Dhahran, a chopped fixed-point approximation of 0.1 accumulated about 0.34 s of timing error after about 100 hours, shifting the tracking window about 687 m. This was a fixed-point representation error, not an IEEE floating-point operation.
Choose binary64 for wider general-purpose precision, binary32 when its smaller memory use suits the task, and binary16 or bfloat16 for suitable low-precision workloads. bfloat16 has eight exponent and seven fraction bits. Exact monetary amounts belong in integer minor units or a decimal type.
Key Takeaways
- A finite binary fraction requires a power-of-two denominator after reduction.
- Short decimal output can conceal representation error.
- Absorption and repeated rounding can change sums and stop floating-point counters.
- Floating-point addition is not associative, so grouping affects reproducibility.
- Cancellation exposes earlier operand error relative to a small difference.
- Conversions need both precision and range checks.
- Format choice depends on required precision, range, and storage cost.
Computer Arithmetic examples
1Trace an adder and judge its result
12 steps
- 1IntroductionBits first, interpretation second
An 8-bit adder keeps eight sum bits and produces a carry-out. The same sum bits can represent an unsigned value or a signed two's complement value. Whether they equal the intended result depends on that reading.
Start with 58 + 27. Both values fit either interpretation, so you can trace the circuit first and ask the range questions afterward.
- 2ExplanationOne position combines three bits
A full adder combines two input bits and the carry-in. Its sum is their XOR. Its carry-out is 1 when at least two of the three inputs are 1.
In a ripple adder, that carry-out becomes the next position's carry-in. Only the lowest position receives the initial carry directly. For ordinary addition, the initial carry is zero.
- 3ExampleWork through the low columns
Write 58 as
0011 1010and 27 as0001 1011. Starting from the right, bit 0 adds 0 and 1 with carry 0, giving sum 1 and carry 0.Bit 1 adds 1 and 1, giving sum 0 and carry 1. Bit 2 then adds 0 and 0 with that carry, giving sum 1 and carry 0. The carry must be included where it arrives, even when both operand bits are zero.
- 4ExampleFinish the sum
Continue through the higher positions. Bit 3 adds two 1s, producing sum 0 and carry 1. Bit 4 combines two 1s with that carry, producing sum 1 and carry 1. Bit 5 combines 1, 0, and 1, producing sum 0 and carry 1. Bit 6 receives that carry and produces 1.
The completed result is
0101 0101, or 85. The final carry is 0, and the signed result remains positive. - 5ChallengeChoose the extension
A signed 4-bit operand
1011must be added to an 8-bit operand. What 8-bit pattern preserves its value, and what would zero extension do?---reveal---
Sign extension gives
1111 1011, still −5. Zero extension gives0000 1011, or +11, changing the input before the addition. The extension follows the operand's interpretation, not the width of the other operand. - 6ExampleReuse the adder for subtraction
Now calculate 58 − 27. Invert
0001 1011to1110 0100, and set the initial carry to 1. Add0011 1010+1110 0100+ 1 to obtain0001 1111, with carry-out 1.The result is 31. For this unsigned subtraction, carry-out 1 means no borrow. Inverting the second operand without the initial 1 would instead produce 30.
- 7Key InsightCarry and overflow answer different questions
Carry-out tells whether an unsigned addition exceeded the available bits. Signed overflow tests the signed range: same-sign addends must not produce an opposite-sign result.
Hardware computes signed overflow by XORing the carry into the sign bit with the carry out. You can have carry without signed overflow, signed overflow without carry, both, or neither.
- 8ExampleA valid unsigned sum can fail signed
Add 90 and 60 in 8 bits. The result is
1001 0110, with carry-out 0. Unsigned 150 fits in the range 0 through 255.Both signed inputs are positive, but the stored signed reading is −106. Signed overflow is therefore 1. The stored pattern is still the low eight bits of 150; it is the signed destination range that cannot hold the exact result.
- 9ChallengeRead both signals
An 8-bit adder adds
1111 0110and0001 0100, producing0000 1010with carry-out 1. What do the unsigned and signed readings tell you?---reveal---
Unsigned 246 + 20 = 266 overflows and stores 10. Signed −10 + 20 = 10 fits, so signed overflow is 0. Opposite-sign addition cannot overflow the signed range, even though this bit calculation has a carry-out.
- 10ConnectionThe program decides how to respond
RISC-V
addreturns low bits without flags or an overflow trap. An unsigned check can compare the sum with an input; a smaller result signals wrapping. Signed checking must use signed relationships instead.Language rules also matter. C unsigned addition wraps, while signed overflow is undefined. Java integer addition wraps, and Python integers grow. A correct bit trace alone does not settle the language-level behavior.
- 11ChallengeConnect subtraction to signed range
An 8-bit ALU computes 100 − (−35). What stored signed value results, and which interpretation needs an overflow report?
---reveal---
The exact signed result is 135, whose low eight bits are
1000 0111, interpreted as −121. Signed subtraction overflows because the inputs have different signs and the result's sign differs from 100. Reading the second pattern as unsigned 221 instead gives 100 − 221, which needs an unsigned borrow. - 12RecapChoose a range test after the bit trace
Addition and subtraction share full adders, with inversion and initial carry selecting subtraction. Extend each input according to its meaning before operating.
Afterward, check carry or borrow for unsigned values and overflow for signed values. Then apply the processor and language rules. Saturating arithmetic makes a separate choice: it clamps an out-of-range result to an endpoint instead of keeping wrapped low bits.
2Build an ALU that compares correctly
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSeveral results, one selected output
- 2ExplanationRepeat a one-bit slice
- 3ExampleDecode one design’s controls
- 4ChallengeBuild NOR from the same gates
- 5ConnectionShift through selected distances
- 6ExplanationReduce the result to Zero
- 7ExampleSee a misleading difference sign
- 8ChallengeInterpret the same patterns twice
- 9ExplanationDescribe a carry before it arrives
- 10ExamplePredict a block’s final carry
- 11ChallengeA generated carry meets a stop
- 12Key InsightSpend gates to shorten the wait
- 13ChallengeKeep comparison correct after a faster adder
- 14RecapSeparate selection, interpretation, and speed
3Follow a product and a quotient through hardware
18 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionProducts combine rows; quotients build decisions
- 2ExampleChoose partial products for 9 times 6
- 3ExampleFinish the selected contributions
- 4Key InsightPreserve the compact multiplier’s carry
- 5ChallengeCheck a narrow unsigned product
- 6ExplanationKeep signed magnitude in unsigned bits
- 7ExplanationSet up Booth’s register
- 8ExampleRun the first two Booth steps
- 9ExampleFinish the signed product
- 10ChallengeTest signed fit after multiplication
- 11ConnectionCompress rows instead of finishing each sum
- 12ExampleBring down the first dividend bits
- 13ExampleComplete the quotient and remainder
- 14ChallengeApply the signed remainder rule
- 15TipUse borrow for the trial subtraction
- 16ChallengeConnect a division shortcut to multiplication
- 17ConnectionRead exceptional RISC-V results
- 18RecapCheck the invariant and the destination
4Decode floating-point bits before doing arithmetic
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionA scale and a limited set of digits
- 2ExampleNormalize the magnitude
- 3ExampleAdd the bias and assemble the fields
- 4ChallengeDecode a new normal value
- 5ExplanationRange does not guarantee integer detail
- 6ExplanationClassify reserved exponents first
- 7ExampleDecode a subnormal without a hidden 1
- 8Key InsightA tiny exact result needs no underflow flag
- 9ChallengeDistinguish infinity from an invalid result
- 10TipTest NaN without equality
- 11ChallengeConnect encoding to gradual underflow
- 12RecapInterpret fields before evaluating a value
5Align, round, and explain precision loss
18 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionKeep information until the rounding decision
- 2ExampleAlign an addition
- 3ExampleNormalize before choosing the neighbor
- 4ExplanationMultiply with one bias correction
- 5ChallengeCorrect an exponent calculation
- 6ExplanationAn even retained bit resolves a tie
- 7ExampleTrack guard, round, and sticky
- 8ChallengeDistinguish a tie from a nearby value
- 9ConnectionThe rounding direction changes negative results
- 10Key InsightFMA preserves a product until after addition
- 11ExplanationDecimal input can arrive already rounded
- 12ExampleA counter reaches a spacing barrier
- 13ChallengePredict a changed grouping
- 14Key InsightExact subtraction can expose earlier error
- 15TipChoose a tolerance that works near zero
- 16ChallengeCheck an integer round trip
- 17ChallengeCombine alignment, sticky, and absorption
- 18RecapLocate the loss of information
Computer Arithmetic practice questions
Set 1: Integer sums, subtraction, and ALU decisions10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
1101?Show answerHide answer
1111 1101 still represents −3; zero extension to 0000 1101 would reinterpret the original pattern as unsigned 13 and change its signed value.Question 6 of 10
0101 and b = 1010, what full-width results do signed slt and unsigned sltu produce?Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
1001 0110. What are its result and Zero output?Show answerHide answer
Set 2: Carry networks and product formation10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
1001 and b = 0111 with initial carry 0. What are group generate, group propagate, and final carry?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
1110 and 0011. What high halves result for signed and unsigned multiplication, and does either product fit its corresponding 4-bit range?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: Signed products, division, and arithmetic shortcuts10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
q = div(a, b), r = rem(a, b), then a wrapping product q × b + r. For a = −2³¹ and b = −1, what happens?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Floating-point fields and exceptional values10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
101 followed by zeros. What is its value?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
0x00000008?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Rounding decisions and precision loss10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 6: Diagnose arithmetic across the datapath10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
0111 1000 from a = 1000 1010. What signed and unsigned less-than results and Zero output follow?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
1010 and 0101 with carry-in 1. Its second operand’s low bit changes from 1 to 0. What happens to final carry and sum?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Absolute tolerance
Absorption
Accumulator
Alignment
Arithmetic logic unit
Arithmetic right shift
B
Barrel shifter
bfloat16
Bit slice
Bnegate
Booth recoding
Borrow
Bounds check
C
Cancellation
Carry generate
Carry lookahead
Carry propagate
Carry-save adder
Carry-select adder
Condition flag
Correct rounding
D
Directed rounding
Dividend
Divisor
E
Exponent bias
F
Floating-point register
Fraction field
01, followed by zeros to fill the field.Full adder
Fused multiply-add
G
Gradual underflow
Group generate
Group propagate
Guard bit
H
Hidden bit
High product half
I
Inexact exception
Infinity
M
Machine epsilon
Modular arithmetic
Multiplexer
Multiplicand
Multiplication latency
Multiplier
1001 selects an unshifted copy and a copy shifted left by three.N
NaN
Non-associativity
Nonrestoring division
Normalization
O
Overflow-corrected sign
P
Partial product
Precision
Q
Quotient
R
Radix-4 Booth recoding
Relative tolerance
Remainder
rem gives −2 for −17 divided by 5 because the nonzero remainder follows the dividend’s sign.Representation error
Restoring division
Ripple-carry adder
Round bit
Round ties to even
S
Saturating arithmetic
Set on less than
slt compares signed operands, while sltu applies unsigned ordering to the same patterns.Shift-and-add multiplication
Sign extension
1010 to 1111 1010 preserves −6; inserting zeros would produce positive 10.Signed overflow
Signed zero
Significand
SRT division
Sticky bit
Subnormal
0x00000002 represents twice the smallest positive subnormal.T
Trap
Two’s complement subtraction
U
Underflow exception
Unit in the last place
Unsigned comparison
1111 is greater than 0001 unsigned, although their signed values are −1 and 1.Unsigned overflow
W
Wallace tree
Z
Zero extension
0000 0000 1111 1010 when extended to 16 bits.Zero output
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.