range of numbers that can be encoded in unsigned binary depends upon no of bits allocated to represent the number
max: \(2^n - 1\)
min: 0
Binary arithmetic
adding two unsigned binary integers
Just like adding in base 10, but carries when gets after 1 (aka would be 2)
basic rules:
\(0_2 + 0_2 = 0_2\).
\(0_2 + 1_2 = 1_2\).
\(1_2 + 0_2 = 1_2\).
\(1_2 + 1_2 = 0_2\), carry \(1_2\)
AKA: \(1_2 + 1_2 = 10_2\)
Binary multiplaction
Exactly what you would expect (aka: same as denary, but the addition thing at the end is subject to rules above)
Note: if there is a situation where you have to do 1+1+1+1 in a column, you will have to carry to the next next column because 1+1+1+1 = 100
Two’s complement
can represent negative integers
Facts independent of no of bits:
If most significant (first) bit is 1, then will be -ve, else +ve (or 0 if all 0).
lowest possible integer when most significant bit 1, and all else 0.
-1 is when all bits 1
highest possible integer is when most significant bit 0, and all else 1.
Observations:
say we have binary number representing \(n_{10}\) of \(k_{10}\) digits. To make a signed integer of \((k+1)_{10}\) digits of value \(-n_{10}\), it is written as 1 prepended to \(2^k-n\) when it is written in binary with \(k\) digits
Above in other words: with \(k+1\) digits, when counting from \(00...00_2\) to \(01...11_2\), you count from \(0\) to \(+2^k -1\), then when counting from \(10...00_2\) to \(11...11_2\), you count from \(-2^k\) to \(-1\).
When I say ‘counting’ here, I mean counting the last \(k\) digits in the binary patterns
The weight of each bit is pow of 2, except for most significant bit, whose weight is negative of corresponding power of two/
Most significant bit sometimes AKA ‘sign bit’
Converting:
Decimal to two’s complement
If non-negative, just convert as if unsigned, but pad begining
if negative:
Method 1:
convert magnitude to binary as if unsigned
prepend 0
flip bits
add \(1_2\)
Method 2:
convert magnitude to binary as if unsigned
prepend 0
flip all bits apart from the least significant bit
Two’s complement to decimal
same as converting binary to decimal, but remember that most significant bit’s value is \(-2^n\)
Subtracting
can subtract B from A by negating B and adding to A.
if this results in a carry, it is ignored because we restrict answer to same numer of bytes started with
Why two’s complement good
don’t need seperate subtraction mechanism: just addition but with complement
the circuits for which are relatively simple
other representations have 2 different representations of 0, this only has 1. Useful because 0 is used heavily when checking for equality. I.e: \(A-B=0 \implies A=B\)
Range
for \(n\) bits the range is \(-2^{n-1}\) to \(2^{n-1}-1\)
e.g for 8 bits: \(-2^7\) to \(2^7 - 1\) = \(-128\) to \(127\)
Fixed Point
can represent numbers with fractional parts i.e: not whole numbers