The binary system is a base 2 numbering system that uses two symbols, 0
and 1
.
Conversion between Decimal and Binary
Decimal to Binary
To convert a decimal number to binary, divide the decimal number by 2 successively and take the remainders in reverse order.
Decimal Number: 10
10 / 2 = 5 (remainder 0)
5 / 2 = 2 (remainder 1)
2 / 2 = 1 (remainder 0)
1 / 2 = 0 (remainder 1)
Binary Number: 1010
Binary to Decimal
To convert a binary number to decimal, multiply the binary digits by the corresponding powers of 2 and sum the results.
Binary Number: 1010
1 * 2^3 + 0 * 2^2 + 1 * 2^1 + 0 * 2^0 = 8 + 0 + 2 + 0 = 10
Decimal Number: 10
Data Representation in Computers
Bits and Bytes
A bit is the smallest unit of information in a binary system, and it can have the value of 0 or 1. A byte is composed of 8 bits and is the basic unit of storage in most computer systems.
Bit: 1
Byte: 01011011
Representation of Positive Integers
Integers are represented using a fixed number of bits (usually 32 or 64 bits) in binary format.
Integer: 10101110
Real: 01000000101011000000000000000000
Representation of Negative Integers
Two’s complement is used.
- Invert all bits.
- Add 1 to the result.
Original Number: 1010
One's Complement: 0101
Two's Complement: 0101 + 1 = 0110
Representation of Fractional Numbers
Real numbers are represented by the IEEE 754 standard, which uses a combination of bits to represent the sign, exponent, and mantissa of the number.
Arithmetic Operations
Binary Addition
- Add the digits starting from the right.
- Carry over if there is a carry.
1010
+ 0110
------
10000
Binary Subtraction
- Subtract the digits starting from the right.
- Borrow if necessary.
1010
- 0110
------
0100
Binary Multiplication
Binary multiplication is performed similarly to decimal multiplication, but only multiplications by 0 and 1 are used.
1010
* 0011
------
10100
1010
------
11110
Logical Operations
Binary AND
A | B | A AND B |
---|---|---|
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
// AND operation
1010 & 1100 = 1000
Binary OR
A | B | A OR B |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
// OR operation
1010 | 1100 = 1110
Binary XOR
A | B | A XOR B |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
// XOR operation
1010 ^ 1100 = 0110
Bit Manipulation
Bit Shift
// Left shift
1011 << 1 = 10110
# Right shift
1011 >> 1 = 101