The binary system is a base 2 numbering system that uses only two symbols, 0
and 1
.
Conversion between Decimal and Binary
Decimal to Binary
To convert a decimal number to binary, the decimal number is divided by 2 successively and the remainders are taken in reverse order.
Example:
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, the binary digits are multiplied by the corresponding powers of 2 and the results are summed.
Example:
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, it can have the value of 0 or 1. A byte consists of 8 bits and is the basic unit of storage in most computer systems.
Example:
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.
Example:
Integer: 10101110
Real: 01000000101011000000000000000000
Representation of negative integers
It uses 2’s complement
- Invert all bits.
- Add 1 to the result.
Example:
Original Number: 1010
1's complement: 0101
2's complement: 0101 + 1 = 0110
Representation of fractional numbers
Real numbers are represented using 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 1 if necessary.
Example:
1010
+ 0110
------
10000
Binary Subtraction
- Subtract the digits, starting from the right.
- Borrow if necessary.
Example:
1010
- 0110
------
0100
Binary Multiplication
Binary multiplication is performed similarly to decimal multiplication, but only using multiplications by 0 and 1.
Example:
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 Shifting
# Left Shift
1011 << 1 = 10110
# Right Shift
1011 >> 1 = 101