Addition in other bases
Objectives
We would like to :- Be able to describe the addition algorithm
- Be able to add in binary
Notes
- If you had to add two longer numbers by hand how would you do this?
3251 First add 1+6 +4976 From basic number facts you know this is 7 ----- 1 3251 Now add the 5 and the 7, +4976 again from basic number facts you know this is 12 ----- But now we have another operation, we need to "carry" the 1 27 11 3251 Now add 1, 2 and 9, +4976 Number fact 1+2 =3 , 3+9 = 12 ----- 227 11 3251 Now add 1, 3 and 4, +4976 Number fact 1+3 =4 , 4+4 = 8 ----- 8227
- What would we have done if the last sum produced a carry?
- This entire system works because we know the addition table for decimal.
+ 0 1 2 3 4 5 6 7 8 9 0 0 1 2 3 4 5 6 7 8 9 1 1 2 3 4 5 6 7 8 9 10 2 2 3 4 5 6 7 8 9 10 11 3 3 4 5 6 7 8 9 10 11 12 4 4 5 6 7 8 9 10 11 12 13 5 5 6 7 8 9 10 11 12 13 14 6 6 7 8 9 10 11 12 13 14 15 7 7 8 9 10 11 12 13 14 15 16 8 8 9 10 11 12 13 14 15 16 17 9 9 10 11 12 13 14 15 16 17 18 - To do the same in binary, we need to memorize the binary addition table.
+ 0 1 0 0 1 1 0 10 - Add 10111112 + 11010102
10111112 1 + 0 = 1 + 11010102 ------- 10111112 1 + 1 = 10 + 11010102 ------- 1 1 10111112 1 + 1 = 10 + 11010102 ------- 01 11 10111112 1 + 1 + 1 = 11 + 11010102 ------- 001 111 10111112 1 + 1 = 10 + 11010102 ------- 1001 1111 10111112 1 + 1 = 10 + 11010102 ------- 01001 11111 10111112 1 + 1 + 1 = 11 + 11010102 ------- 001001 11111 10111112 1 + 1 + 1 = 11 + 11010102 ------- 110010012 - You should be able to add in binary.
- We could do the same in octal and hex, what would we need?
- Let's think about addition in a fixed number of bits.
- What could go wrong?
- We could have overflow.
- How do we detect this? (A carry out from the last bit)
- You should be able to add numbers in binary.
- The addition algorithm
ADDITION Input A, B two strings of digit in the same base. Output c = a+b in the same base. Assume A[0] is the least significant digit of A, B[0] of B. Assume that Sum(digit, digit, carry) will compute the sum in the given base
- pad either a or b on the left with 0 so that they are the same size.
- carry ← 0
- For i ← 0 to A.length()-1
- (C[i],carry) ← Sum(A[i],B[i], carry)
- if carry > 0
- C[A.length()] = carry