Section 3.1 Addition and Subtraction
Computers do arithmetic in the binary number system. The operations are really quite easy to understand if you recall all the details of performing arithmetic in the decimal number system by hand. Since most people do addition on a calculator these days, let us review all the steps required when doing it by hand. This discussion will be followed by exercises asking you to develop the algorithms to perform addition and subtraction in binary and in hexadecimal. Consider two two-digit numbers,carries | |||
sum |
Algorithm 3.1.1. Add Fixed-Width (N-Digit) Integers in the Decimal Number System.
-
For
sum
%carry
Algorithm 3.1.1 works because we use a positional notation when writing numbersโa digit one place to the left counts ten times more.
Carry from the current position one place to the left is always 0 or 1.
The reason we use 10 in the
/
and%
operations is that there are exactly ten digits in the decimal number system: 0, 1, 2,โฆ, 9.Since we are working in an N-digit system, we must restrict our result to N digits. The final carry,
is either or and is part of the result, along with the N-digit sum.
Algorithm 3.1.2. Subtract Fixed-Width (N-Digit) Integers in the Decimal Number System.
Subtracting
-
For
-
If
difference
-
Else
-
While
and -
If
-
While
difference
-
One Hexadecimal | Four Binary | Unsigned |
Digit | Digits (bits) | Decimal |