Playing with Numbers: Binary
Binary (Base-2)
The binary system is a foundational concept in computing, representing numeric values using only two symbols: 0 and 1.
Digits
The only digits used are 0
and 1
.
Converting Binary to Decimal
To convert a binary number to its decimal equivalent, you multiply each binary digit by 2 raised to the power of its position (starting from 0 on the right) and sum the results.
Example: Convert 10011
in binary to decimal.
The positions are 4, 3, 2, 1, 0 from left to right.
(1 * 2⁴) + (0 * 2³) + (0 * 2²) + (1 * 2¹) + (1 * 2⁰)
= (1 * 16) + (0 * 8) + (0 * 4) + (1 * 2) + (1 * 1)
= 16 + 0 + 0 + 2 + 1
= 19
Converting Decimal to Binary
To convert a decimal number to binary, you repeatedly divide the number by 2, keeping track of the remainders. The binary representation is the sequence of remainders read in reverse order.
Example: Convert 6
in decimal to binary.
- 6 ÷ 2 = 3 remainder 0
- 3 ÷ 2 = 1 remainder 1
- 1 ÷ 2 = 0 remainder 1
Reading the remainders in reverse order gives 110
. So, 6 in decimal is 110
in binary.
Binary Addition
Binary addition follows these simple rules for each bit:
- 0 + 0 = 0 (carry 0)
- 0 + 1 = 1 (carry 0)
- 1 + 0 = 1 (carry 0)
- 1 + 1 = 0 (carry 1)
Two’s Complement Representation
This is a method to represent both positive and negative numbers in binary.
- Sign Bit: The leftmost bit (Most Significant Bit) indicates the sign.
0
for positive,1
for negative. - Range: With n bits, you can represent numbers from -2ⁿ⁻¹ to 2ⁿ⁻¹ - 1.
- Negating a Number:
- Flip all the bits (0s become 1s and vice versa).
- Add 1 to the result.
Example: Find the 4-bit Two's Complement for -4.
- Start with 4 in decimal which is
0100
in binary. - Flip the bits:
1011
. - Add 1:
1011 + 1 = 1100
.
So, -4 in decimal is represented as 1100
in 4-bit Two's Complement.
Converting from Two's Complement: If the sign bit is 0, convert as usual. If it's 1, it's a negative number. To find its value, negate it again (flip bits and add 1), convert the result to decimal, and put a negative sign in front.
Read more on the Wikipedia page for Binary numbers.