Write and . The operands occupy the integer points of the square . The exact sum is representable precisely when
The upper boundary is , and the lower boundary is . Within the operand square, the closed band between these lines is representable. The triangle below the lower line has negative overflow, and the triangle above the upper line has positive overflow. The boundary lines themselves are included.
Consequently overflow occurs exactly when or . Negative overflow requires two negative operands; positive overflow requires two nonnegative operands. Same-sign operands alone are not sufficient: their exact sum must cross a range endpoint. Opposite-sign operands never overflow on addition. In terms of the stored wrapped result, addition overflows exactly when the operands have equal sign bits and the result has the opposite sign bit.
The illustration uses , so and , and marks every permissible operand pair. The general region follows from the same two inequalities for arbitrary .
An -bit two's complement word represents the integer
The leading bit has negative weight. Words beginning with zero encode the nonnegative values; words beginning with one encode the negative values. Equivalently, interpret the whole word as unsigned and subtract when its leading bit is one. For example, the four-bit words 0111, 1000, and 1111 encode , , and respectively. The range is asymmetric: the most negative value has no positive counterpart in the same number of bits.
For a nonzero representable magnitude, complementing all bits and adding one obtains its negative modulo . Fixed-width addition can therefore use the same low-order binary numeral system addition circuitry for signed and unsigned operands; interpreting the result as signed requires detecting integer overflow.
A D flip-flop stores one bit. On each active clock edge, it samples the input D and changes its stored output Q to that sampled value after the propagation delay. Between active edges, it holds the value. In the ideal discrete model,
where is the input sampled at edge and is the state just after that edge. This assumes D meets the required setup time and hold time; asynchronous set or reset inputs, if present, are inactive.
For nonnegative integer x and positive integer y, initialize the quotient to zero and subtract one divisor at a time:
q := 0; r := x;
WHILE r >= y DO
  r := r-y;
  q := q+1
END
The loop invariant is , , , with x and y unchanged. It is true initially. A body execution changes to and keeps nonnegative because of the guard. The nonnegative integer loop variant strictly decreases by , so termination follows. At exit the guard supplies ; hence
There are exactly body executions. Under the unit-cost model, the time complexity including initialization and the final test is , which is for integer . This is a bound in the value of x, rather than in its encoded bit length.
In a least-significant-first bit-serial comparator, the new pair has higher significance than every pair already processed. Equal new bits preserve the earlier result; unequal new bits decide the new result regardless of earlier bits. Use a left fold starting at equality:
type Bit = Int
data LEG = Lt | Eq | Gt deriving (Eq, Show)

step :: LEG -> (Bit,Bit) -> LEG
step old (a,b)
  | a < b = Lt
  | a > b = Gt
  | otherwise = old

compare :: [Bit] -> [Bit] -> LEG
compare as bs = foldl step Eq (pairs as bs)
  where
    pairs [] [] = []
    pairs (a:as) [] = (a,0) : pairs as []
    pairs [] (b:bs) = (0,b) : pairs [] bs
    pairs (a:as) (b:bs) = (a,b) : pairs as bs
Inputs have the precondition that each Bit is 0 or 1. Equal-length inputs are the physical circuit case; pairs also gives a defined unsigned meaning to unequal lengths by padding the shorter input with high-order zeros. Ordinary zip would silently discard significant unmatched bits.
After pairs the fold accumulator compares and . Equal new bits add the same amount. If , the new difference has magnitude , exceeding the maximum magnitude of the earlier difference. This proves the accumulator invariant and gives
For the four pairs in the source, the states are Lt, Gt, Gt, Lt, so the final result compares correctly.
Use two stored bits with symmetric meanings:
Swapping the two numbers interchanges and and fixes equality. Decode the outputs by
Thus only the equality output needs extra logic gates, namely two inversions and an AND gate, or a NOR gate. Code 11 is unused. Initialize both D flip-flops to zero before a new pair of numbers so the starting state is Eq. In normal operation only the three valid codes are reachable.
Let denote the state after the next active clock edge. In the truth table, an entry is the two-bit next-state code, and – marks a don't-care value for the unused current state 11:
Current
(Eq)
(Lt)
(Gt)
(unused)
For each input column, 01 forces , 10 forces , and the two equal-input columns copy the current code. Thus this compact truth table specifies all twelve valid combinations of state and input, or twenty-four individual next-state bits:
Arrange each four-variable Karnaugh map in Gray code order down the rows and across the columns. For the row strings are 0100, 0100, ----, 1110; for they are 0001, 1011, ----, 0001. The maps are drawn alongside the state-transition diagram above.
In the map, group the whole ab=01 column to obtain . Group rows 11,10 with columns 00,01 to obtain . Group those same rows with columns 01,11 to obtain . The unused-state row permits these larger groups. Symmetrically, in the map group column ab=10, rows 01,11 with columns 11,10, and those same rows with columns 10,00 (wrapping around the map). This gives
These expressions drive the D inputs of the two D flip-flops. With , both copy their stored bit. With , they force Lt; with , they force Gt. The equations also specify a harmless extension at unused code 11: equal inputs retain it and unequal inputs recover to a valid comparison state. Correct reset is still required. This extension was chosen using don't-cares; the circuit is not claimed to recover from every invalid state without reset.
A D flip-flop stores one bit. At its specified active clock edge, it samples and, after its clock-to-Q delay, makes equal to that sampled value. Between active clock edges it retains the stored value. The input must meet the setup and hold time requirements around the sampling edge; a level-sensitive latch would have different behavior.
For a finite-state sequential circuit, encode the present state in a bank of D flip-flops. Feed their outputs and the external inputs to combinational logic computing the next-state function , and connect those outputs to the flip-flop inputs. A common clock signal then performs the simultaneous update
Output combinational logic computes for a Moore machine or for a Mealy machine. Since any finite next-state and output table is a Boolean function, it has a Boolean circuit implementation. Initialization specifies the starting state, and unused state encodings require either a recovery rule or an initialization assumption. The clock period must accommodate propagation through the D flip-flops and intervening combinational logic before the next sampling edge.
A particularly transparent design uses six D flip-flops in a one-hot encoding. Let mean that face is displayed. Initialize and , and wire the next-state inputs as a ring:
All six D flip-flops share the same active clock edge. Each pulse moves the single stored to the next position, giving the state-transition diagram cycle . The representation invariant “exactly one is high” holds after initialization and is preserved by rotation. Six D flip-flops are more than the three-bit theoretical minimum, but their simple wiring gives a complete implementation without requiring that minimum.
Figure 1.
One-hot ring state register and the six lamp patterns, including the original opposite diagonals on faces 2 and 3
. Details.
Decode the seven lamps by their positions, with denoting top, middle and bottom, and denoting left and right. Let be the center lamp. In the original figure, face 2 uses top-left and bottom-right, while face 3 uses top-right and bottom-left plus center; the two diagonals must therefore have different controls.[ref] The required OR gate decoder is
For example, only the center is high in state , the first diagonal is high in state , and in state both outer columns are high while the center is low. This verifies all six layouts directly.
To implement the switch behavior, use a rapid common clock signal and a sampled enable , high while the switch is pressed. Each next-state input is then selected between its advancing value and its own stored value:
One multiplexer per D flip-flop implements that selection. While enabled the electronic dice advances; otherwise every D flip-flop reloads its own value and the display holds. The enable supplied to this synchronous design must be stable at sampling edges. A reset or preset facility must establish the specified one-hot initial state: an all-zero ring does not start itself.
With a rapid clock signal, uncertainty in human release timing makes the final face practically unpredictable. The sequential circuit itself is deterministic; this observation alone is not a proof that its six outcomes have equal probabilities.
The printed word “even” conflicts with the displayed numbers: all ten listed prime numbers are odd, and is the only even prime number. The scan confirms that wording.[ref] We first construct the detector for the explicitly listed numbers, then add as requested. The literal even-prime detector is also given below.
Let the five input bits be with value . Every listed number has . For that plane, the four-variable Karnaugh map is
The entire plane is zero. Five valid groups in the displayed Karnaugh map give the product terms
Including , their accepted numbers are respectively , , , , and . Their union is exactly the ten listed numbers. Hence an explicit Boolean circuit is: invert where needed, feed the five products into five AND gates, combine those outputs with an OR gate, and AND with . Its output is
Any gate with more than two inputs can be replaced by a tree of two-input gates. To include the exceptional prime number , detect its exact binary representation and add one OR branch:
If “even prime” is read literally instead of following the listed numbers, the complete first detector is simply
All three formulas classify all possible inputs, including and as nonprime.
The opcode occupies bits , the arithmetic logic unit operation is wired directly to , and an immediate operand uses all of . A three-register instruction needs fifteen register-selection bits, whereas an immediate instruction must retain independent source and destination selectors outside .
Thus put and in the ten bits , and place in five of , where it can overlap the unused immediate operand of a register instruction. One valid instruction encoding is
Bits are unused for a three-register instruction. In an immediate instruction, has no effect because its read value is deselected by the ToAlu multiplexer. In a store, selects the address and selects the data; must be zero to suppress the incidental register write. These observations follow the original datapath, particularly its direct memory-address connection and the connection from the ToAlu output to memory write data.[ref]
A MIPS R-type instruction has the 32-bit instruction encoding
For add $x,$y,$z, the processor register indices are , and , while . The main opcode selects the R-type family and the function field selects addition. The register file reads its two operands from instruction bits 25:21 and 20:16. In the original datapath, RegDst=1 selects bits 15:11 as the destination, ALUSrc=0 selects the second register file output, and ALUFunc=ADD makes the arithmetic logic unit add its inputs. The result returns to wdata; RegWrite=1 writes it to at the active clock edge. The zero output is irrelevant here.[ref]
A MIPS I-type instruction instead has the instruction encoding
For addi $x,$y,n, , , and the low sixteen bits contain the immediate operand. The register file supplies to the first arithmetic logic unit input. Set RegDst=0 to select bits 20:16 for the destination, and ALUSrc=1 to select the extended immediate operand for the second input. The opcode directly requests addition, so ALUFunc=ADD and RegWrite=1. The second register file read is unused. The returned result is written into .
The sign extension circuit retains the low sixteen bits and copies bit 15 into all sixteen new high positions:
Thus sign extension preserves the signed two's complement value: 0x7fff becomes 0x00007fff, whereas 0x8000 becomes 0xffff8000. For both instructions, the architectural result above assumes no signed overflow; the full MIPS architecture specifies an overflow exception, which is outside this simplified datapath.
Add zero extension alongside sign extension, and a multiplexer controlled by a new signal ExtSign to select between them before the existing immediate-input connection. Equivalently, make the extender itself selectable:
Decode ori to ExtSign=0, RegDst=0, ALUSrc=1, RegWrite=1 and ALUFunc=OR. The arithmetic logic unit then performs bitwise OR between and the zero-extended immediate operand and writes the result to . Extend the arithmetic logic unit's control decoding if OR was not already available. Decode addi to ExtSign=1; the new signal is irrelevant for MIPS R-type instructions because ALUSrc=0.
Zero extension matters even when the most significant immediate bit is one: ori with 0x8000 must only affect the low half of the destination, whereas sign extension would incorrectly force every high bit to one.[ref]
Make the code a leaf procedure called array_diff, copy the four argument processor registers into the temporaries used above, and replace the final label by a return. The copies are real addu instructions, avoiding an unexplained move pseudo-instruction:
array_diff:
        addu  $t0,$a0,$zero
        addu  $t1,$a1,$zero
        addu  $t2,$a2,$zero
        addu  $t3,$a3,$zero
        # insert the code of (i), including its initial zero-count test
        # use the local label array_diff_done in place of done
array_diff_done:
        jr    $ra
        sll   $zero,$zero,0
In the literal insertion, the done: line from (i) is the array_diff_done: line displayed here; it is not a second return block. Under the usual calling convention, temporary processor registers are caller-saved. This procedure calls no other procedure and changes no saved processor registers, so it needs no stack frame or saved return address.
For a 32-bit constant , define and using its unsigned binary representation. Load it with lui followed by ori; both are single MIPS instructions. For base addresses and count , the main program is:
main:
        lui   $a0,H_A
        ori   $a0,$a0,L_A
        lui   $a1,H_B
        ori   $a1,$a1,L_B
        lui   $a2,H_C
        ori   $a2,$a2,L_C
        lui   $a3,H_N
        ori   $a3,$a3,L_N
        jal   array_diff
        sll   $zero,$zero,0
main_after_call:
        # c now contains the differences; continue the main program here
Here each H_... and L_... is an assembler-time numeric constant, not an executed operation. lui places the high half and clears the low half; ori inserts the low half without sign extension. Thus
The jal instruction saves the return address after its branch delay slot in $ra; jr $ra resumes at main_after_call. A main routine that itself needs to return to a caller must save its incoming $ra before jal and restore it afterwards.
Use byte addresses, so adjacent 32-bit array elements are four bytes apart. The following MIPS instructions include harmless sll $zero,$zero,0 instructions in every branch delay slot; the second load is followed by another independent instruction before its value is consumed, also accommodating an early MIPS architecture with a load-use delay. All mnemonics here denote individual machine instructions.
        beq   $t3,$zero,done  # n=0: do not access any array
        sll   $zero,$zero,0
loop:
        lw    $t4,0($t0)      # current a element
        lw    $t5,0($t1)      # current b element
        addiu $t0,$t0,4       # advance a; also separates lw from its use
        subu  $t6,$t4,$t5     # current difference, modulo 2^32
        sw    $t6,0($t2)      # store current c element
        addiu $t1,$t1,4
        addiu $t2,$t2,4
        addiu $t3,$t3,-1      # one fewer element remains
        bne   $t3,$zero,loop
        sll   $zero,$zero,0
done:
A loop invariant at the head of the loop, after completed iterations, is that the three addresses point to elements , the count is , and every output element before equals the corresponding difference. One iteration reads element , stores its difference and advances to , preserving the loop invariant. The remaining count is a nonnegative loop variant decreasing by one, so the loop ends with .
The code uses subu to avoid signed-overflow traps: the suffix does not restrict the operands to unsigned values. Its precise result is
For representable signed differences this is exactly . If trapping signed arithmetic is required instead, use sub and assume all differences are representable. The arrays must occupy valid word-aligned storage with no address wrap; the usual separate output array avoids overwriting unread inputs.
An access control list is attached to an object, such as a file, and lists which subjects or groups may perform which operations. Access requires checking the requesting identity against that object's list. A security capability is an unforgeable reference to an object carrying specified rights; possessing valid authority is what permits access. Protected storage or another integrity mechanism must prevent users manufacturing stronger security capabilities.
The traditional Unix owner/group/other read-write-execute permissions are a compact, restricted access control list: the inode records the owner, group and permission bits, and the operating system compares these against the caller's credentials.
An already-open file descriptor can behave like a limited handle carrying rights, but that does not change the identity-based nature of the initial pathname permission check.
Use three D flip-flops whose stored bits represent . Initialize them to . The Moore machine's output is this stored binary representation, and its state transition table is:
Present Next
Treat the two unused state encodings as don't-care conditions when minimizing the sum of products. With juxtaposition for AND, for OR and a bar for NOT, one minimal choice is
For , the required ones at and cannot share one valid implicant: their differing bits would force inclusion of required zeros. Pair with the unused to get , and with unused to get . Neither term can lose a Boolean literal without covering a required zero.
For , state is isolated from every other required one and from the unused states by required zeros, so it forces the three-Boolean literal term . State pairs with unused to give . Finally is a single Boolean literal. Thus the three expressions are minimal sum of products expressions under the stated unused-state convention. In fact these choices also recover from , so initialization into an unused state eventually joins the intended modulo-six counter cycle.
Let the stored bits be , with most significant. The required Gray code transitions give
Connect directly to the first D flip-flop's data input and feed through one NOT gate to the second input. Drive both enable inputs with and both clock inputs with the same clock. Thus holds both stored bits; takes the next Gray-code counter state at the active clock edge. Reset initializes .
Figure 1.
Enabled Gray-code counter and synchronous SOS sequencer: all stored bits share one clock
. Details.
With ordinary uncomplemented outputs, one NOT gate is minimal: wiring alone cannot produce . If a D flip-flop already provides a complementary output, that output supplies the inversion without an external logic gate. This is a Moore machine because its output depends only on stored state; controls transitions.
Use a synchronous counter cascade, with the three-bit modulo-six counter advancing on every active clock edge and the Gray-code counter advancing only when the old binary state is . Its enable can therefore be
On the six valid binary states, only at . Both digital counters sample the same clock: at an edge leaving , the binary output becomes and simultaneously advances to the next Gray code. At all other edges holds. Starting from , this gives exactly the listed 24-state sequence. Use the shared clock and an enable, rather than making a combinational terminal-state signal into a new clock.[ref]
For the output , every state with has . For , the only extra high states are with binary state , and with binary state or . On valid states these conditions are and , respectively. Hence
The lower circuit in the figure implements this with an AND for , an exclusive or on , an AND with , and an OR with . The resulting Morse code output blocks, in Gray code order , are
Across the two middle blocks these join to three three-clock highs separated by one-clock lows; the first and last blocks provide the three single-clock highs of each S. The specified table is a repeating SOS symbol pattern; its wraparound has a one-clock low, rather than an added inter-message pause. The output is a Moore machine decoding of current stored bits; its value changes after those bits settle.