Computer Arithmetic

Learn how processor hardware does arithmetic. Add and subtract with one two's complement adder, tell carry from overflow, and build an ALU that also compares numbers and runs logic operations. Follow how multipliers and dividers work, from shift-and-add circuits to Booth's algorithm and fast tree multipliers, including the RISC-V instructions. Then encode numbers in IEEE 754 floating point, add, multiply and round them as the hardware does, and explain why results such as 0.1 + 0.2 are not exact.

IntermediateLesson 3 of 6 in Computer Organization and Architecture Course

What you will learn

  1. 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 adder
      Add 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 results
      Tell carry from overflow, detect each one with simple hardware or a short instruction sequence, and know what processors and languages do when it happens.
  2. 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 slices
      Combine 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 ALU
      Produce 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 lookahead
      Explain why carries make ripple adders slow, and compute carries in advance with generate and propagate signals.
  3. 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 add
      Multiply 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 fast
      Handle two's complement operands, recode multipliers with Booth's algorithm, and explain how tree multipliers reach high speed.
    • Divide integers and handle the special cases
      Divide 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.
  4. 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 formats
      Write 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 numbers
      Recognize the reserved exponent patterns, explain gradual underflow, and predict the results and flags of exceptional operations.
  5. 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 numbers
      Align, operate, normalize and round in the order floating-point hardware does, and use the RISC-V floating-point instructions.
    • Round results correctly
      Apply 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 errors
      Explain why familiar decimal values are inexact in binary, why floating-point addition is not associative, and how absorption, cancellation and conversions cause real failures.

Computer Arithmetic study guide

5 chapters

1

Add 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:

si=ai⊕bi⊕ci ci+1=aibi+aici+bici

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 2n. 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−b=a+b‾+1.

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
InterpretationExtension ruleExtending 4-bit 1110 to 8 bits
Signed two's complementCopy the sign bit1111 1110, still −2
UnsignedInsert zeros0000 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 2n.
  • 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 2n−1; signed two's complement values run from −2n−1 through 2n−1−1. 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
OperationUnsigned overflowSigned overflow
AdditionCarry out of the top bit is 1Same-sign inputs produce a result of the opposite sign
SubtractionA borrow is neededDifferent-sign inputs produce a result whose sign differs from the first input

For signed addition or subtraction, hardware can use

V=cn−1⊕cn,

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 2n; 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.
2

Design 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:

a‾⋅b‾=a+b‾.

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 wordSelected result
0000AND
0001OR
0010Add
0110Subtract
0111Signed set on less than
1100NOR

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:

Zero=r0+r1+⋯+rn−1‾.

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 2n, 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

Lesssigned=sign(a−b)⊕V.

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:

Lessunsigned=cn‾

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 patternsSigned comparisonUnsigned comparison
0111, 10007 < −8 is false7 < 8 is true
1000, 0111−8 < 7 is true8 < 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 2n−1 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

gi=aibi,pi=ai+bi.

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

ci+1=gi+pici.

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:

c1=g0+p0c0 c2=g1+p1g0+p1p0c0 c3=g2+p2g1+p2p1g0+p2p1p0c0 c4=g3+p3g2+p3p2g1+p3p2p1g0+p3p2p1p0c0.

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

G=g3+p3g2+p3p2g1+p3p2p1g0, P=p3p2p1p0.

Its output carry is G+Pc0. 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 si=pi⊕ci. 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.
3

Multiply 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:

StepMultiplier low bitShifted multiplicandRunning product
110000 01100000 0110
200000 11000000 0110
310001 10000001 1110
400011 00000001 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 2k 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 8x+2x=10x. 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:

PairAccumulator operation
10Subtract the multiplicand
01Add the multiplicand
00 or 11Leave 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

dividend=quotient×divisor+remainder.

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.

CalculationQuotientRemainder
−7 divided by 2−3−1
7 divided by −2−31
−7 divided by −23−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 2k−1 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.
4

Represent 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

(−1)s×1.f×2e.

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
FormatSign bitsExponent bitsFraction bitsBiasPrecision
binary1615101511 bits
binary32182312724 bits
binary6411152102353 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:

value=(−1)S(1+Fraction)2E−Bias.

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 0.112=1.12×2−1. 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

1.1000112=1+12+132+164=1.546875.

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 3.40×1038, with smallest positive normal 2−126 and about seven significant decimal digits. binary64 reaches approximately 1.80×10308, with smallest positive normal 2−1022 and about 15–16 significant digits. binary16 has maximum 65,504, smallest positive normal 2−14, smallest positive subnormal 2−24, 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 2e up to 2e+1, adjacent normal values are spaced 2e−23 apart. This spacing is an ulp, a unit in the last place. Just above 1 it is 2−23, often called machine epsilon. At 224 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 fieldFraction fieldMeaning
All zerosZeroSigned zero
All zerosNonzeroSubnormal
All onesZeroSigned infinity
All onesNonzeroNaN

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:

value=(−1)S×0.f×21−Bias.

For binary32, 0x00000001 is 2−149 and 0x00400000 is 2−127. For binary64 the smallest positive value is 2−1074. 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, 2−126/2=2−127 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.
5

Compute 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):

  1. Write the operands as 1.0002×2−1 and −1.1102×2−2.
  2. Align the second to −0.1112×2−1.
  3. Subtract the magnitudes: 1.0002−0.1112=0.0012.
  4. Normalize to 1.0002×2−4, 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 9.999+0.01610 at scale 101. The exact intermediate is 10.01510 at that scale. Normalize to 1.00151×102 and round to 1.002×102. 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:

Eresult=Ea+Eb−Bias

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 1.0002×1.1102=1.1102. Sign XOR is 1, giving −1.1102×2−3=−0.21875.

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 a=1+2−23, b=1−2−23, and c = −1. Their exact product is 1−2−46. A separate multiply rounds this to 1, so the addition returns zero. FMA retains the small product difference and returns −2−46.

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
DirectionRule
roundTiesToEvenNearest value; an exact tie chooses a final significand bit of 0
roundTowardPositiveToward +∞
roundTowardNegativeToward −∞
roundTowardZeroToward zero
roundTiesToAwayNearest 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, 1.00112 rounds to 1.0102, and 1.01012 also rounds to 1.0102. 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

1.00010012×23.

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 1.0012×23=9. 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 2−24; for binary64 it is 2−53. 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

∣a−b∣≤max⁡(atol,rtolmax⁡(∣a∣,∣b∣)).

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 1+2−23. Subtracting 1 gives about 1.1920929×10−7 instead of 1.0×10−7, 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 253, 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

5 Walkthroughs

1

Trace an adder and judge its result

12 steps
Follow addition and subtraction through an 8-bit adder, then distinguish the signals used for unsigned and signed range checks.
  1. 1
    IntroductionBits 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.

  2. 2
    ExplanationOne 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.

  3. 3
    ExampleWork through the low columns

    Write 58 as 0011 1010 and 27 as 0001 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.

  4. 4
    ExampleFinish 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.

  5. 5
    ChallengeChoose the extension

    A signed 4-bit operand 1011 must 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 gives 0000 1011, or +11, changing the input before the addition. The extension follows the operand's interpretation, not the width of the other operand.

  6. 6
    ExampleReuse the adder for subtraction

    Now calculate 58 − 27. Invert 0001 1011 to 1110 0100, and set the initial carry to 1. Add 0011 1010 + 1110 0100 + 1 to obtain 0001 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.

  7. 7
    Key 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.

  8. 8
    ExampleA 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.

  9. 9
    ChallengeRead both signals

    An 8-bit adder adds 1111 0110 and 0001 0100, producing 0000 1010 with 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.

  10. 10
    ConnectionThe program decides how to respond

    RISC-V add returns 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.

  11. 11
    ChallengeConnect 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.

  12. 12
    RecapChoose 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.

2

Build an ALU that compares correctly

14 steps
Select arithmetic and logic results, correct signed less-than after overflow, and shorten the carry path.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSeveral results, one selected output
  2. 2
    ExplanationRepeat a one-bit slice
  3. 3
    ExampleDecode one design’s controls
  4. 4
    ChallengeBuild NOR from the same gates
  5. 5
    ConnectionShift through selected distances
  6. 6
    ExplanationReduce the result to Zero
  7. 7
    ExampleSee a misleading difference sign
  8. 8
    ChallengeInterpret the same patterns twice
  9. 9
    ExplanationDescribe a carry before it arrives
  10. 10
    ExamplePredict a block’s final carry
  11. 11
    ChallengeA generated carry meets a stop
  12. 12
    Key InsightSpend gates to shorten the wait
  13. 13
    ChallengeKeep comparison correct after a faster adder
  14. 14
    RecapSeparate selection, interpretation, and speed
3

Follow a product and a quotient through hardware

18 steps
Trace unsigned multiplication, Booth recoding, and restoring division, then apply signed rules and width checks.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionProducts combine rows; quotients build decisions
  2. 2
    ExampleChoose partial products for 9 times 6
  3. 3
    ExampleFinish the selected contributions
  4. 4
    Key InsightPreserve the compact multiplier’s carry
  5. 5
    ChallengeCheck a narrow unsigned product
  6. 6
    ExplanationKeep signed magnitude in unsigned bits
  7. 7
    ExplanationSet up Booth’s register
  8. 8
    ExampleRun the first two Booth steps
  9. 9
    ExampleFinish the signed product
  10. 10
    ChallengeTest signed fit after multiplication
  11. 11
    ConnectionCompress rows instead of finishing each sum
  12. 12
    ExampleBring down the first dividend bits
  13. 13
    ExampleComplete the quotient and remainder
  14. 14
    ChallengeApply the signed remainder rule
  15. 15
    TipUse borrow for the trial subtraction
  16. 16
    ChallengeConnect a division shortcut to multiplication
  17. 17
    ConnectionRead exceptional RISC-V results
  18. 18
    RecapCheck the invariant and the destination
4

Decode floating-point bits before doing arithmetic

12 steps
Encode a normal value, relate spacing to precision, and classify zeros, subnormals, infinities, and NaNs.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionA scale and a limited set of digits
  2. 2
    ExampleNormalize the magnitude
  3. 3
    ExampleAdd the bias and assemble the fields
  4. 4
    ChallengeDecode a new normal value
  5. 5
    ExplanationRange does not guarantee integer detail
  6. 6
    ExplanationClassify reserved exponents first
  7. 7
    ExampleDecode a subnormal without a hidden 1
  8. 8
    Key InsightA tiny exact result needs no underflow flag
  9. 9
    ChallengeDistinguish infinity from an invalid result
  10. 10
    TipTest NaN without equality
  11. 11
    ChallengeConnect encoding to gradual underflow
  12. 12
    RecapInterpret fields before evaluating a value
5

Align, round, and explain precision loss

18 steps
Trace floating-point operations, use guard/round/sticky information, and predict absorption, cancellation, and conversion errors.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionKeep information until the rounding decision
  2. 2
    ExampleAlign an addition
  3. 3
    ExampleNormalize before choosing the neighbor
  4. 4
    ExplanationMultiply with one bias correction
  5. 5
    ChallengeCorrect an exponent calculation
  6. 6
    ExplanationAn even retained bit resolves a tie
  7. 7
    ExampleTrack guard, round, and sticky
  8. 8
    ChallengeDistinguish a tie from a nearby value
  9. 9
    ConnectionThe rounding direction changes negative results
  10. 10
    Key InsightFMA preserves a product until after addition
  11. 11
    ExplanationDecimal input can arrive already rounded
  12. 12
    ExampleA counter reaches a spacing barrier
  13. 13
    ChallengePredict a changed grouping
  14. 14
    Key InsightExact subtraction can expose earlier error
  15. 15
    TipChoose a tolerance that works near zero
  16. 16
    ChallengeCheck an integer round trip
  17. 17
    ChallengeCombine alignment, sticky, and absorption
  18. 18
    RecapLocate the loss of information

Computer Arithmetic practice questions

60 Practice Questions in 6 sets

Set 1: Integer sums, subtraction, and ALU decisions10 Practice Questions

Question 1 of 10

A full adder receives operand bits 1 and 0 with carry-in 1. What sum bit and carry-out does it produce?
  1. Sum 1, carry 0
  2. Sum 1, carry 1
  3. Sum 0, carry 1
  4. Sum 0, carry 0
Show answerHide answer
Answer: C
The three inputs total two, written as binary 10, so the sum bit is 0 and the carry is 1. A sum bit of 1 would result from ignoring the carry-in and XORing only the two operand bits; a full adder must include all three inputs.

Question 2 of 10

An 8-bit subtractor inverts the second operand but accidentally leaves initial carry-in at 0. What signed result does it produce for 42 − 17?
  1. 24
  2. 25
  3. 26
  4. −25
Show answerHide answer
Answer: A
Inversion without the initial 1 computes a − b − 1, so this circuit returns 42 − 17 − 1 = 24. The intended 25 requires the extra carry-in that completes the two’s complement of 17; inversion by itself is not negation.

Question 3 of 10

What are carry-out and signed overflow for the 8-bit addition 118 + 19?
  1. Carry 1, overflow 0
  2. Carry 0, overflow 0
  3. Carry 1, overflow 1
  4. Carry 0, overflow 1
Show answerHide answer
Answer: D
The sum is 137, below the unsigned maximum 255, so carry-out is 0. Its stored pattern has sign bit 1 despite two positive signed inputs, so signed overflow is 1; using the unsigned range alone would incorrectly declare that both readings fit.

Question 4 of 10

Which ALU component selects one result from the candidate AND, OR, and adder outputs?
  1. The carry chain
  2. The output multiplexer
  3. The sign-extension circuit
  4. The operand register
Show answerHide answer
Answer: B
The output multiplexer passes one candidate result according to the operation controls. The carry chain helps calculate the sum but does not choose between arithmetic and logic paths, while the operand register holds a value rather than selecting an ALU result.

Question 5 of 10

What 8-bit pattern preserves the value of the signed 4-bit operand 1101?
  1. 0000 1101
  2. 1111 1101
  3. 1000 1101
  4. 0000 0011
Show answerHide answer
Answer: B
The input represents −3, so sign extension copies its leading 1 into every added high bit. The result 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

For 4-bit inputs a = 0101 and b = 1010, what full-width results do signed slt and unsigned sltu produce?
  1. slt: 0001; sltu: 0000
  2. slt: 0001; sltu: 0001
  3. slt: 0000; sltu: 0000
  4. slt: 0000; sltu: 0001
Show answerHide answer
Answer: D
Signed readings are 5 and −6, so 5 < −6 is false and slt returns 0. Unsigned readings are 5 and 10, so sltu returns 1; applying one signed interpretation to both instructions would miss why the same bits produce different comparisons.

Question 7 of 10

What does unsigned 8-bit saturating addition return for 220 + 70?
  1. 255
  2. 34
  3. 254
  4. 290
Show answerHide answer
Answer: A
The exact sum 290 is above the unsigned 8-bit maximum, so saturation clamps it to 255. Keeping only the low eight bits would give 34, but that is wrapping arithmetic; saturation preserves an endpoint instead of the residue modulo 256.

Question 8 of 10

A 64-bit barrel shifter uses power-of-two shift stages. Which stages are selected for a shift by 37?
  1. 32, 4, and 2
  2. 16, 8, 4, and 1
  3. 32, 4, and 1
  4. 32, 8, and 1
Show answerHide answer
Answer: C
The selected distances must add to 37, and 32 + 4 + 1 does so. Choosing 32, 4, and 2 gives 38, an off-by-one shift; the stage distances represent the binary decomposition of the requested amount, not the bit positions of the value being shifted.

Question 9 of 10

An 8-bit wrapping routine computes (115 + 29) − 40, then uses the final signed result. What result and overflow history does it have?
  1. 104; both operations overflow signed
  2. 104; only the addition overflows signed
  3. −152; only the subtraction overflows signed
  4. −112; neither operation overflows signed
Show answerHide answer
Answer: A
The first sum 144 stores −112 and overflows signed. Subtracting 40 from −112 gives −152, which wraps to 104 and also overflows signed; modular arithmetic recovers the fitting final value even though testing only the initial addition would miss the second overflow.

Question 10 of 10

An 8-bit ALU subtracts two identical patterns 1001 0110. What are its result and Zero output?
  1. Result 0000 0000, Zero 0
  2. Result 1111 1111, Zero 0
  3. Result 0000 0000, Zero 1
  4. Result 0000 0001, Zero 0
Show answerHide answer
Answer: C
Subtracting a bit pattern from itself produces all-zero result bits, and the NOR reduction therefore sets Zero to 1. A result of all 1s would come from inverting the second operand but forgetting the initial +1, which would compute one less than the intended difference.
Set 2: Carry networks and product formation10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

With OR-propagate, what are generate and propagate for operand bits 1 and 1?
  1. Generate 1, propagate 0
  2. Generate 1, propagate 1
  3. Generate 0, propagate 1
  4. Generate 0, propagate 0
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

How many bits can the full unsigned product of a 7-bit operand and a 9-bit operand require?
  1. 9 bits
  2. 15 bits
  3. 18 bits
  4. 16 bits
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What full 8-bit product and retained low 4-bit result come from unsigned 11 × 3?
  1. Full 0010 0001; low 0001
  2. Full 0001 0001; low 0001
  3. Full 0010 0001; low 0010
  4. Full 0001 1110; low 1110
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A 4-bit block has group generate 0 and group propagate 1. What output carry results for carry-in 0 and for carry-in 1?
  1. 1 for carry-in 0; 1 for carry-in 1
  2. 0 for carry-in 0; 0 for carry-in 1
  3. 0 for carry-in 0; 1 for carry-in 1
  4. 1 for carry-in 0; 0 for carry-in 1
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What does a carry-save stage do with three partial-product words?
  1. Produces one word with a full carry chain
  2. Produces two words after a full carry chain
  3. Produces three words without a full carry chain
  4. Produces two words without a full carry chain
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

In a 32-bit bounds check, the index is −2 and the nonnegative signed-range length is 20. What does an unsigned comparison of index ≥ length report?
  1. False, so the index is accepted
  2. True, so the index is rejected
  3. True, as signed −2 exceeds 20
  4. False, as −2 is clamped to zero
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An RV32 routine needs the complete product of an unsigned operand times another unsigned operand. Which results must it combine?
  1. mulh as high half and mul as low half
  2. mul as high half and mulhu as low half
  3. mulhu as high half and mul as low half
  4. mulhsu as high half and mulh as low half
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A 4-bit OR-propagate lookahead block adds a = 1001 and b = 0111 with initial carry 0. What are group generate, group propagate, and final carry?
  1. G = 1, P = 1, carry = 1
  2. G = 0, P = 1, carry = 0
  3. G = 1, P = 0, carry = 1
  4. G = 0, P = 1, carry = 1
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A 4-bit multiplier receives patterns 1110 and 0011. What high halves result for signed and unsigned multiplication, and does either product fit its corresponding 4-bit range?
  1. Signed high 1111, does not fit; unsigned high 0010, fits
  2. Signed high 1111, fits; unsigned high 0010, does not fit
  3. Signed high 0000, fits; unsigned high 0010, does not fit
  4. Signed high 1111, fits; unsigned high 0000, fits
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An overflowing signed subtraction has stored sign bit 0. What signed less-than result should the ALU produce?
  1. 0
  2. The carry-out bit
  3. The Zero output
  4. 1
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

What shift-and-add expression equals 12x when all intermediates fit and the language permits the shifts?
  1. (x << 3) + (x << 2)
  2. (x << 3) + (x << 1)
  3. (x << 4) + (x << 2)
  4. (x << 3) + x
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A pipelined multiplier has four-cycle latency and accepts one new multiplication each cycle. When can a second independent multiplication start after the first starts?
  1. Four cycles later
  2. Three cycles later
  3. Two cycles later
  4. One cycle later
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Which quantity supplies the sign of a nonzero remainder in truncating signed division?
  1. The divisor
  2. The quotient
  3. The smaller-magnitude operand
  4. The dividend
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What quotient and remainder does RISC-V signed division produce for 23 divided by −6?
  1. Quotient −4, remainder −1
  2. Quotient −3, remainder 5
  3. Quotient −3, remainder −5
  4. Quotient 3, remainder 5
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

In a Booth step, A = 0, multiplicand = −7, and the low-bit pair is 10. What accumulator value is needed before shifting?
  1. −7
  2. 0
  3. +7
  4. −1
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A compact unsigned multiplier’s high-half addition produces carry 1. Where must that carry go during the next combined right shift?
  1. Into the high half’s top position
  2. Into the multiplier’s low position
  3. Into the next step’s low carry-in
  4. Outside the stored product entirely
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An RV32 routine computes q = div(a, b), r = rem(a, b), then a wrapping product q × b + r. For a = −2³¹ and b = −1, what happens?
  1. q = −2³¹, r = 0; reconstruction returns 2³¹ − 1
  2. q = 2³¹ − 1, r = −1; reconstruction returns −2³¹
  3. q = −2³¹, r = 0; reconstruction returns −2³¹
  4. q = 2³¹, r = 0; reconstruction returns −2³¹
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A four-bit restoring divider has partial remainder 2 and divisor 11 before a trial subtraction. What trial pattern and action are required?
  1. Trial 0111; keep and write 1
  2. Trial 1001; restore and write 0
  3. Trial 1001; keep and write 1
  4. Trial 0111; restore and write 0
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A 4-bit Booth implementation uses a 5-bit accumulator for multiplicand −8 and multiplier 1. What are the accumulator’s first update and the final 8-bit product?
  1. First −8 (11000); product 1111 1000
  2. First +8 (01000); product 1111 1000
  3. First +8 (01000); product 0000 1000
  4. First −8 (11000); product 0000 1000
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A signed routine replaces truncating division of −29 by 8 with a right shift. What bias and shifted result preserve the quotient?
  1. Add 7, then shift to −3
  2. Add 0, then shift to −4
  3. Add 3, then shift to −4
  4. Add 8, then shift to −2
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

What true exponent does a normal binary32 exponent field of 123 encode?
  1. −4
  2. 4
  3. −3
  4. 123
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What does a binary32 pattern with an all-ones exponent and a nonzero fraction represent?
  1. A subnormal
  2. Infinity
  3. NaN
  4. A normal value
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A normal binary32 value has sign 1, exponent field 125, and fraction 101 followed by zeros. What is its value?
  1. −0.15625
  2. −0.40625
  3. −1.625
  4. −0.8125
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What binary32 sign, exponent field, and fraction prefix encode −10.5?
  1. Sign 1; exponent 130; fraction 10101…
  2. Sign 1; exponent 124; fraction 0101…
  3. Sign 0; exponent 130; fraction 0101…
  4. Sign 1; exponent 130; fraction 0101…
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What is the value of positive binary32 subnormal pattern 0x00000008?
  1. 2⁻¹⁴⁹
  2. 2⁻¹⁴⁷
  3. 2⁻¹⁴⁶
  4. 2⁻¹²⁶
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Two positive normal floating-point significands multiply to 11.01₂ at an initial true exponent of 4. What normalized product results before rounding?
  1. 1.101₂ × 2⁵
  2. 1.101₂ × 2³
  3. 1.101₂ × 2⁴
  4. 1.010₂ × 2⁵
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Two positive normal binary32 values are 2⁻⁸⁰ and 2⁻⁶⁰. Their exact product is representable in binary32. What result class and underflow flag arise under default handling?
  1. Subnormal; underflow set
  2. Normal; underflow clear
  3. Zero; underflow set
  4. Subnormal; underflow clear
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A binary32 result is computed as (−6.0)/(−0.0) under default handling, then compared equal to itself. What value, newly raised flag, and equality result occur?
  1. −∞; division-by-zero; true
  2. +∞; division-by-zero; true
  3. +∞; invalid; false
  4. NaN; invalid; false
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A binary32 format is replaced by one with the same exponent field but two fewer fraction bits. At magnitudes from 2¹⁰ through values below 2¹¹, how does spacing change?
  1. From 2⁻¹³ to 2⁻¹⁵
  2. From 2⁻¹⁰ to 2⁻⁸
  3. From 2⁻¹³ to 2⁻¹¹
  4. From 2⁻¹³ to 2⁻¹²
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Which RISC-V instruction category writes its result to an integer register even though it compares floating-point inputs?
  1. Floating-point additions such as fadd.s
  2. Floating-point comparisons such as flt.s
  3. Floating-point products such as fmul.s
  4. Fused multiply-adds such as fmadd.s
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

An exact four-bit-significand tie lies between 1.110₂ and 1.111₂. What does nearest-even select?
  1. 1.111₂
  2. 1.101₂
  3. 1.110₂
  4. 10.000₂
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A normalized result retains significand 1.011₂ with guard/round/sticky 100. What is the nearest-even rounded significand?
  1. 1.011₂
  2. 1.100₂
  3. 1.010₂
  4. 1.101₂
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Using four-bit significands and nearest-even rounding, what is 2.75 + 0.375?
  1. 3.125
  2. 3.25
  3. 2.75
  4. 3.0
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Which reduced fraction has an exact finite binary expansion: 7/16, 7/20, 7/12, or 7/10?
  1. 7/16
  2. 7/20
  3. 7/12
  4. 7/10
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A normalized four-bit-significand result has exact bits 1.111101₂ at true exponent 5. Under nearest-even rounding, what normalized result is stored?
  1. 1.111₂ × 2⁵
  2. 1.000₂ × 2⁶
  3. 1.000₂ × 2⁵
  4. 1.111₂ × 2⁶
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

In binary32 under nearest-even rounding, a stored accumulator equals 2²⁶. A loop adds stored value 3 exactly four times, rounding after each addition. What final value results?
  1. 2²⁶ + 8
  2. 2²⁶ + 12
  3. 2²⁶
  4. 2²⁶ + 16
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

In binary32 nearest-even arithmetic, let a = 1 + 2⁻¹², b = 1 − 2⁻¹², c = −1. What do separate a × b + c and fused multiply-add return?
  1. Both return −2⁻²⁴
  2. Separate returns 0; fused returns −2⁻²⁴
  3. Separate returns −2⁻²⁴; fused returns 0
  4. Both return 0
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A positive finite binary32 value overflows when multiplied by 2. With roundTowardNegative, what result and flags arise under default handling?
  1. Positive infinity; overflow and inexact
  2. Largest finite positive; underflow and inexact
  3. Positive infinity; division-by-zero and inexact
  4. Largest finite positive; overflow and inexact
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

In binary32 nearest-even arithmetic, x = 1 + 2⁻²³ is stored exactly. A program evaluates (x − 1) × 2²³. What result occurs, and does the subtraction introduce error?
  1. 1; the subtraction is exact
  2. 0; the subtraction drops 2⁻²³
  3. 1; the subtraction rounds up
  4. 2; the subtraction yields 2⁻²²
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A negative exact value −2.3 is rounded to an integer. What are the results toward zero and toward negative infinity?
  1. Toward zero −3; toward negative −2
  2. Toward zero −2; toward negative −2
  3. Toward zero −2; toward negative −3
  4. Toward zero −3; toward negative −3
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

A floating-point calculation returns NaN. What kind of test should a program use to recognize it?
  1. Equality with a stored NaN constant
  2. A dedicated NaN test such as isnan
  3. A test that the value equals itself
  4. A test that the sign bit equals 1
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An 8-bit ALU subtracts b = 0111 1000 from a = 1000 1010. What signed and unsigned less-than results and Zero output follow?
  1. Signed 0; unsigned 0; Zero 0
  2. Signed 1; unsigned 1; Zero 0
  3. Signed 0; unsigned 1; Zero 1
  4. Signed 1; unsigned 0; Zero 0
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A 4-bit OR-propagate block adds 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?
  1. Carry stays 1; sum changes 0000 to 1111
  2. Carry changes 1 to 0; sum changes 1111 to 0000
  3. Carry changes 1 to 0; sum changes 0000 to 1111
  4. Carry stays 0; sum changes 0000 to 1111
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A program multiplies unsigned 8-bit patterns 0xFE and 0x02. It takes the upper byte from their signed product and the lower byte from their unsigned product. What 16-bit value is assembled?
  1. 0xFFFC instead of 0x01FC
  2. 0x01FC instead of 0xFFFC
  3. 0xFF02 instead of 0x01FC
  4. 0x00FC instead of 0x01FC
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

An RV32 routine computes divu and remu for dividend 37 and divisor 0, then tests whether q × divisor + remainder equals 37 using wrapping arithmetic. What does the test establish?
  1. It fails because the quotient is all ones
  2. It traps before the equality can be tested
  3. It passes because the quotient is zero
  4. It passes even though division by zero occurred
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

In the normal binary32 interval from 64 up to 128, what is the spacing between adjacent values?
  1. 2⁻¹⁶
  2. 2⁻¹⁷
  3. 2⁻²³
  4. 2⁻¹⁸
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

In binary32 nearest-even arithmetic, a = 1 + 2⁻²², b = 1 − 2⁻²², and c = −1 are exact inputs. What do separate multiply-add and FMA return?
  1. Separate 0; FMA −2⁻⁴⁴
  2. Separate −2⁻⁴⁴; FMA −2⁻⁴⁴
  3. Separate 0; FMA +2⁻⁴⁴
  4. Separate −2⁻²²; FMA −2⁻⁴⁴
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A four-bit-significand model rounds each operation nearest-even. It computes (16 + 1.25) − 16. What result is returned?
  1. 0
  2. 1.25
  3. 2
  4. 1
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A wide integer 67,108,867 is converted to binary32 and back to a wide integer under nearest-even rounding. The program then subtracts the original integer. What difference results?
  1. +5
  2. −3
  3. 0
  4. −1
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

After an RV32 unsigned addition, the stored sum is smaller than the first input in unsigned order. What conclusion follows?
  1. The addition necessarily overflowed signed
  2. The addition has neither carry nor overflow
  3. The first input was necessarily negative
  4. The addition wrapped past the unsigned maximum
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

78 Key Terms, each with its definition

A

Absolute tolerance
An absolute tolerance sets a magnitude-independent error allowance, useful when approximate finite values lie near zero.
An absolute floor prevents a near-zero comparison from depending only on a vanishing relative allowance.
Absorption
Absorption occurs when adding a small value leaves a larger floating-point operand unchanged because rounding removes the contribution.
A binary32 counter at 2²⁴ can stop increasing when the program repeatedly adds 1.
Accumulator
An accumulator holds a running arithmetic result; Booth’s algorithm uses an n + 1-bit accumulator for n-bit operands.
The extra accumulator bit makes it possible to subtract a most-negative multiplicand without overflow.
Alignment
Alignment shifts a smaller-exponent significand right so floating-point operands share the larger exponent before addition or subtraction.
Aligning exponents 6 and 2 shifts the second significand four positions to the right.
Arithmetic logic unit
An arithmetic logic unit is a combinational datapath circuit that selects arithmetic or logic results from operands and control inputs.
Changing the operation controls lets the same pair of register outputs feed an addition or a bitwise AND.
Arithmetic right shift
An arithmetic right shift moves bits toward lower positions while copying the original sign bit into newly opened high positions.
Shifting signed −10 right by one yields −5; shifting −9 the same way also yields −5.

B

Barrel shifter
A barrel shifter combines power-of-two shift stages to shift a word by a selected distance through a fixed number of logic levels.
A 32-bit barrel shifter selects the 16- and 4-position stages to produce a shift by 20.
bfloat16
bfloat16 is a 16-bit floating-point format with one sign bit, eight exponent bits, and seven fraction bits, emphasizing range over precision.
Its exponent width matches binary32’s, while its shorter fraction preserves much less detail.
Bit slice
A bit slice is the portion of a repeated datapath circuit that handles one operand bit position and its local signals.
The top slice supplies overflow information, while each intermediate slice passes a carry onward.
Bnegate
Bnegate is a shared control in a sliced ALU that inverts the second operand and sets the initial carry-in for subtraction.
Setting Bnegate while selecting the adder changes a + b into a + NOT(b) + 1.
Booth recoding
Booth recoding replaces binary multiplier runs with signed contributions, allowing multiplication through additions and subtractions.
A multiplier containing one long run of 1s can be represented by a power of two minus another power of two.
Borrow
A borrow indicates that an unsigned subtraction needs a higher-place unit because the first operand is smaller than the second.
Subtracting unsigned 12 from 5 needs a borrow even though the circuit still returns a fixed-width pattern.
Bounds check
A bounds check tests whether an index belongs to the valid range of an array before that index is used to access an element.
An unsigned comparison against a nonnegative signed-range length rejects both negative and excessive indices.

C

Cancellation
Cancellation removes shared leading digits when nearly equal values are subtracted, making earlier operand errors large relative to the difference.
An exact subtraction can still reveal a poor relative result if its two inputs were already rounded.
Carry generate
A carry-generate signal indicates that a bit position produces a carry regardless of its carry-in because both operand bits are 1.
When generate is 1, the next carry is 1 even if no lower position supplied an incoming carry.
Carry lookahead
Carry lookahead computes carries from generate and propagate expressions, reducing the serial carry dependence of a ripple adder.
A lookahead unit can compute a block’s outgoing carry before each internal carry has rippled through.
Carry propagate
A carry-propagate signal describes whether an incoming carry can pass through a bit position; this design uses operand OR.
With inputs 1 and 0, propagate is 1 and generate is 0, so the incoming carry determines the outgoing carry.
Carry-save adder
A carry-save adder compresses three input words into a sum word and a carry word without propagating carries across the full width.
Several carry-save levels reduce partial-product rows before a final carry-propagating addition.
Carry-select adder
A carry-select adder calculates a block for both possible incoming carries and selects one precomputed result when the carry arrives.
Duplicating upper-block arithmetic trades more circuit area for a shorter wait on the lower block.
Condition flag
A condition flag is a processor status bit that records a property of a completed operation for later testing by another instruction.
A branch can inspect x86’s overflow flag after addition to detect an out-of-range signed result.
Correct rounding
Correct rounding returns the exact mathematical operation rounded according to the destination format and selected rounding direction.
Conforming basic arithmetic agrees numerically for identical inputs, destination format, and rounding direction.

D

Directed rounding
Directed rounding selects a representable neighbor in a specified direction: toward positive infinity, negative infinity, or zero.
For a negative inexact result, toward-zero and toward-negative rounding can choose different neighbors.
Dividend
A dividend is the value being divided, equal to the quotient times the divisor plus the remainder.
In −17 divided by 5 with truncation, the dividend is −17, the quotient −3, and the remainder −2.
Divisor
A divisor is the value by which a dividend is divided; for ordinary integer division it must be nonzero.
Dividing 29 by 6 leaves a remainder smaller than the positive divisor 6.

E

Exponent bias
An exponent bias is a fixed offset added to a normal number’s true exponent before storing it as an unsigned field.
A binary32 true exponent of 5 is stored as 132 because the format’s bias is 127.

F

Floating-point register
A floating-point register holds an operand or result for floating-point instructions; RISC-V F and D use registers f0 through f31.
A floating-point comparison writes its 0-or-1 result to an integer register instead of this bank.
Fraction field
The fraction field stores the significand bits after its binary point, leaving the leading bit implicit in normal values.
A normal significand of 1.01₂ stores a fraction beginning 01, followed by zeros to fill the field.
Full adder
A full adder combines two operand bits and a carry-in, producing a sum bit and a carry-out for the next position.
With three input 1s, the full adder outputs sum 1 and carry 1, representing the binary value 11.
Fused multiply-add
A fused multiply-add evaluates a product plus an addend with one final rounding, retaining the product’s intermediate precision.
FMA can preserve a small difference erased when a product is rounded before an opposing addend is added.

G

Gradual underflow
Gradual underflow represents tiny values with decreasing significant precision through subnormals instead of immediately replacing them with zero.
An exact half of the smallest normal binary32 value survives as a nonzero subnormal.
Group generate
A group-generate signal indicates that a block of bits produces an outgoing carry independently of the carry entering the block.
A high bit that generates a carry makes the block generate, even if its lowest bit stops incoming carries.
Group propagate
A group-propagate signal indicates that every position in a block can pass an incoming carry through to the block’s output.
Four OR-propagate bits must all be 1 for a four-bit block’s group propagate to be 1.
Guard bit
The guard bit is the first extra bit beyond the retained significand, helping distinguish values below, at, or above halfway.
A guard bit of 0 places the discarded portion below half an ulp after normalization.

H

Hidden bit
The hidden bit is the implicit leading 1 of a normal binary significand, which the format supplies without storing it.
binary32 obtains 24 bits of normal precision from a 23-bit fraction field and its hidden leading 1.
High product half
The high product half contains the more significant n bits of a full 2n-bit product of two n-bit operands.
A nonzero high half shows that an unsigned product loses information when stored in only n bits.

I

Inexact exception
The inexact exception records that a delivered floating-point result differs from the exact mathematical result because of rounding.
A rounded value can set inexact during an ordinary calculation without producing overflow or invalid operation.
Infinity
An infinity is a signed floating-point special value encoded with an all-ones exponent and zero fraction.
Positive infinity plus a finite value stays positive infinity, while infinity minus itself produces NaN.

M

Machine epsilon
Machine epsilon commonly denotes the gap between 1 and the next larger representable value, equal to 2⁻²³ for binary32.
The gap just above 1 is twice the usual binary32 relative nearest-rounding bound of 2⁻²⁴.
Modular arithmetic
Modular arithmetic retains the residue after division by a fixed modulus; n-bit wrapping arithmetic uses a modulus of 2ⁿ.
Unsigned 8-bit 250 + 20 returns 14 because 270 and 14 differ by one complete modulus of 256.
Multiplexer
A multiplexer selects one of several candidate input signals and passes it to an output according to control bits.
An ALU output multiplexer can select an AND result while the adder simultaneously computes a sum.
Multiplicand
A multiplicand is the operand whose shifted copies form partial products selected by the bits of the multiplier.
In shift-and-add multiplication of 9 by 5, shifted copies of 9 contribute at multiplier bits 0 and 2.
Multiplication latency
Multiplication latency is the time from starting one multiplication until its result becomes available to a dependent operation.
A pipelined multiplier can accept a new product each cycle even when the latency is several cycles.
Multiplier
A multiplier is the operand whose bits select shifted multiplicand contributions in a binary multiplication algorithm.
The multiplier pattern 1001 selects an unshifted copy and a copy shifted left by three.

N

NaN
A NaN is an unordered floating-point special value representing an undefined numerical result, encoded with a nonzero fraction and all-one exponent.
Zero divided by zero produces NaN, and comparing that result equal to itself returns false.
Non-associativity
Non-associativity means that changing the grouping of an operation can change its result; intermediate rounding causes it in floating-point addition.
A parallel sum can change its last bits when a different thread count changes the reduction grouping.
Nonrestoring division
Nonrestoring division carries a negative partial remainder into the next step and corrects through the next addition or a final add-back.
A negative final partial remainder must be increased by the divisor to obtain the final remainder.
Normalization
Normalization moves a nonzero significand into the required leading-digit form and changes the exponent to preserve its value.
A sum with significand 10.1₂ shifts right once while its exponent increases by one.

O

Overflow-corrected sign
The overflow-corrected sign is the subtraction result’s sign XOR signed overflow, giving the correct signed less-than decision.
A wrapped positive true difference can appear negative until the overflow bit corrects the comparison.

P

Partial product
A partial product is one shifted contribution to a multiplication result, selected by a multiplier bit or a recoded digit.
For unsigned binary multiplication, each ordinary partial product is either a shifted multiplicand or zero.
Precision
Precision is the number of significant digits available in a numerical format, limiting detail at a particular scale.
Increasing the exponent can increase binary32 spacing even though its 24-bit precision remains fixed.

Q

Quotient
A quotient is the division result before the remainder; truncating signed integer division rounds it toward zero.
For −19 divided by 4, truncation gives quotient −4, while rounding down would give −5.

R

Radix-4 Booth recoding
Radix-4 Booth recoding handles two multiplier bits per step with signed digits from −2 through +2 to reduce partial-product count.
A radix-4 multiplier needs fewer partial-product rows than a design creating one row per multiplier bit.
Relative tolerance
A relative tolerance sets an acceptable comparison error in proportion to the magnitudes of the finite values being compared.
A fixed relative tolerance permits a larger absolute difference for values near one million than near one.
Remainder
A remainder is the value left after subtracting quotient times divisor from the dividend under the chosen division convention.
RISC-V rem gives −2 for −17 divided by 5 because the nonzero remainder follows the dividend’s sign.
Representation error
Representation error is the difference between an intended value and its stored approximation when the format cannot represent it exactly.
The decimal value 0.1 has a repeating binary expansion and must be approximated in binary32.
Restoring division
Restoring division tries a divisor subtraction and reverses it when the trial fails, producing one quotient bit per step.
If a trial needs a borrow, the hardware adds back the divisor and records quotient bit 0.
Ripple-carry adder
A ripple-carry adder chains full adders so that each carry-out supplies the next more significant bit’s carry-in.
A carry created at bit 0 may have to pass through many slices before the top result bit settles.
Round bit
The round bit is the second extra bit beyond the retained significand, contributing information about the discarded tail.
Guard 1 and round 1 indicate a value above halfway even before the sticky bit is examined.
Round ties to even
Round ties to even chooses the nearest representable value and, at an exact halfway case, chooses a retained significand ending in 0.
At a whole-number tie, 6.5 rounds to 6 and 7.5 rounds to 8 under this rule.

S

Saturating arithmetic
Saturating arithmetic clamps an out-of-range result to the largest or smallest value supported by its destination format.
Saturating unsigned 8-bit 240 + 30 returns 255, preventing a bright pixel from wrapping to a dark value.
Set on less than
Set on less than produces the full-width integer 1 if a specified operand comparison is true and integer 0 otherwise.
RISC-V slt compares signed operands, while sltu applies unsigned ordering to the same patterns.
Shift-and-add multiplication
Shift-and-add multiplication examines multiplier bits sequentially and accumulates the corresponding shifted multiplicand values.
A six-bit sequential multiplier performs six bit steps even when most multiplier bits are zero.
Sign extension
Sign extension widens a two’s complement pattern by copying its sign bit into the new high positions, preserving its value.
Extending signed 1010 to 1111 1010 preserves −6; inserting zeros would produce positive 10.
Signed overflow
Signed overflow occurs when the exact result lies outside the destination’s two’s complement range, regardless of carry-out.
A positive 8-bit sum that becomes a negative stored pattern can indicate signed overflow.
Signed zero
A signed zero is a floating-point zero with a positive or negative sign bit; the two compare equal but retain some sign effects.
Positive 1 divided by negative zero returns negative infinity under default floating-point handling.
Significand
A significand contains the significant binary digits of a floating-point value, including the implicit leading bit when normal.
The normal value 1.101₂ × 2³ has significand 1.101₂ and true exponent 3.
SRT division
SRT division selects quotient digits from leading divisor and partial-remainder bits, allowing several quotient bits per step.
A wrong entry in the selection table can corrupt a quotient despite otherwise correct arithmetic hardware.
Sticky bit
The sticky bit is the OR of all discarded bits beyond guard and round, recording whether any nonzero bit exists in that tail.
Guard 1, round 0, and sticky 1 mean above halfway, so treating the result as a tie would be wrong.
Subnormal
A subnormal is a nonzero floating-point value with a zero exponent field, a leading significand 0, and the minimum normal scale.
The binary32 pattern 0x00000002 represents twice the smallest positive subnormal.

T

Trap
A trap transfers control to exception-handling code when an instruction triggers a condition that requires special processing.
A trapping MIPS addition transfers control when its signed result exceeds the register’s range.
Two’s complement subtraction
Two’s complement subtraction adds the inverted second operand and an initial carry of 1 to the first operand.
The same 8-bit adder can compute 19 + 6 or 19 − 6 by changing its inversion and carry controls.

U

Underflow exception
The underflow exception under default handling requires both a tiny result and inexactness, so an exact subnormal does not trigger it.
Dividing the smallest normal binary32 value by 2 produces an exact subnormal without underflow.
Unit in the last place
A unit in the last place, or ulp, is the spacing associated with the least significant retained position at a chosen scale.
In the binary32 interval from 16 to 32, adjacent normal values are 2⁻¹⁹ apart.
Unsigned comparison
An unsigned comparison orders patterns as nonnegative binary values, so a high leading bit contributes positive weight.
The pattern 1111 is greater than 0001 unsigned, although their signed values are −1 and 1.
Unsigned overflow
Unsigned overflow occurs when an exact result falls outside zero through the largest value representable at the destination width.
An unsigned 8-bit sum of 230 and 40 stores 14, while carry-out reports that 270 did not fit.

W

Wallace tree
A Wallace tree reduces partial-product rows through layers of carry-save compression before a final addition produces the product.
Parallel row reduction shortens the path compared with adding one complete partial product after another.

Z

Zero extension
Zero extension widens an unsigned pattern by inserting zeros in its new high positions without changing its numerical value.
An unsigned byte containing 250 becomes 0000 0000 1111 1010 when extended to 16 bits.
Zero output
The Zero output is an ALU status signal that is 1 only when every result bit is zero, usually formed by a reduction NOR.
Subtracting equal operand patterns sets Zero even when those patterns represent negative signed values.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started