You can perform arithmetic or logical operations on bits Bit operations
(位元運算) Arithmetic
(算數) Logical
(邏輯)
4.1
Arithmetic
Operations
Adding Bits
Number of 1s------------
None
One
Two
Three Result------------
0
1
0
1 Carry------------
1
1 Most computer use the two’s complement method of integer representation
Adding numbers in two’s complement is like adding the number in decimal, if there is a carry, it is added to the next column
If there is a carry after addition of the leftmost digits, the carry is discarded
Rule of Adding Integers in Two's Complement
Add 2 bits and propagate the carry to the next column. If there is a final carry after the left most column addition, discard it.
The term overflow describes a condition in which a number is not within the range defined by the bit allocation
For example4, the range is -28-1 to +28-1-1, which is -128 to 127. The result of the addition (130) is not in this range
Note
Range of numbers in two’s complementrepresentation
- (2N-1) ---------- 0 ----------- +(2N-1 –1)
Two’s Complement Numbers Visualization
Note
When you do arithmetic operations (算術運算) on numbers in a computer, remember that each number and the result should be in the range defined by the bit allocation (配置)
Subtraction in Two's Complement
X – Y = X + (-Y) To subtract in two‘s complement, just negate (two’s complement, 指使用二的補數對數值進行變更正負號) the second number to be subtracted and add
The steps are as follows:
Check the signs
If the signs are the same, add the numbers and assign (分配) the sign to the result
If the signs are different, compare the absolute values (絕對值), subtract the smaller from the larger, and use the sign of the larger for the result
Move the decimal points to make the exponents the same.
Add or subtract the mantissas (假數)
Normalize the result before storing in memory
Check for any overflow
Example
Add two floats:0 10000100 101100000000000000000000 10000010 01100000000000000000000 Solution The exponents are 5 and 3. The numbers are:+25 * 1.1011 and +23 * 1.011Make the exponents the same.(+25 * 1.1011) + (+25 * 0.01011) +25 * 10.00001After normalization +26 * 1.000001, which is stored as:0 10000101 000001000000000000000000
4.2
Logical
Operations
Unary and Binary Operations
Logical operation on bits can be unary (one input, 單一) or binary (two inputs)
Comments