Skip to main content

Sum of digits processor

Short answer

Design uses repeated subtraction to extract digits: while N>0, set R=N, Q=0, subtract 10 from R until R<10 incrementing Q; add R to sum, set N=Q. Datapath has registers N,R,Q,SUM, subtractor, incrementer, adder, comparators, and muxes. Controller is a 6-state FSM. For n=345, sum is 12.

Design a single purpose processor to determine the sum of digits of an integer. Start the design from the function computing the desired result, FSMD, datapath and controller.

Assumption: n is an unsigned 16-bit integer (0 to 65535). The decimal digits are extracted with "mod 10" and "div 10", implemented by repeated subtraction (there is no hardware divider).

Step 1: Function

 SumDigits(n):
   sum = 0
   while (n > 0):
       q = 0; r = n
       while (r >= 10): r = r - 10; q = q + 1    // q = n div 10, r = n mod 10
       sum = sum + r
       n = q
   output sum

Step 2: FSMD

StateConditionActionsNext
S0 waitstart = 0done = 0S0
S0start = 1N = n, SUM = 0S1
S1 testN > 0noneS2
S1N = 0noneS5
S2 initalwaysR = N, Q = 0S3
S3 divideR >= 10R = R - 10, Q = Q + 1S3
S3R < 10noneS4
S4 accumulatealwaysSUM = SUM + R, N = QS1
S5 outputalwaysout = SUM, done = 1S0
 S0 -> S1 -(N>0)-> S2 -> S3 -(R>=10, loop)-> S3
        |                 |(R<10)
       (N=0)              v
        v               S4 -> S1
       S5 -> S0

Step 3: Datapath

 n -> [N] <- mux(n, Q) ;  [N > 0] comparator -> gtz
 [R] <- mux(N, R-10) <- subtractor(R, const 10) ; [R >= 10] -> ge10
 [Q] <- mux(0, Q+1) <- incrementer
 [SUM] <- mux(0, SUM+R) <- adder
 SUM -> out

Components: registers N, R, Q, SUM; a subtractor (R - 10), an incrementer, an adder, comparators (N > 0, R >= 10), and muxes for N, R, Q and SUM.

Controller

Six-state FSM, 3-bit state register. Inputs: start, gtz, ge10. Outputs: N_ld, R_ld/R_sel, Q_clr/Q_inc, SUM_clr/SUM_ld, done.

 start, status flags --> +-------------+   +-----------+
 (from datapath)         | Next-state  |-->| State     |
                         | logic       |   | register  |
                         +------^------+   +-----+-----+
                                |   current state |
                                +-----------------+
                                                  v
                                           +-------------+
                                           | Output logic|--> control
                                           +-------------+    signals

Trace n = 345: (Q, R) = (34, 5): sum 5; n = 34 -> (3, 4): sum 9; n = 3 -> (0, 3): sum 12; n = 0 -> output 12.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Embedded System chapter 2 questions →