The binary representation of integers is a way to express integer numbers using only two digits: 0 and 1.
Understanding Binary
Binary is a base-2 number system, contrasting with the base-10 (decimal) system we commonly use. In the decimal system, each digit position represents a power of 10 (e.g., 1s, 10s, 100s). In binary, each position represents a power of 2 (e.g., 1s, 2s, 4s, 8s).
Representing Unsigned Integers in Binary
Unsigned integers are non-negative whole numbers. Converting an unsigned decimal integer to binary involves finding the combination of powers of 2 that sum up to the decimal value.
For example, let's convert the decimal number 10 to binary:
- The largest power of 2 less than or equal to 10 is 8 (23). So we have one 8.
- 10 - 8 = 2. The next power of 2 is 4 (22), but we don't need it.
- The next power of 2 is 2 (21). We need one 2.
- The next power of 2 is 1 (20), but we don't need it.
Therefore, 10 in decimal is (1 x 23) + (0 x 22) + (1 x 21) + (0 x 20) which translates to 1010 in binary.
Representing Signed Integers in Binary
Signed integers can be positive or negative. Several methods exist for representing signed integers in binary, the most common being:
-
Sign and Magnitude: The leftmost bit represents the sign (0 for positive, 1 for negative), and the remaining bits represent the magnitude (absolute value) of the number. For example, using 8 bits, +5 would be 00000101 and -5 would be 10000101. This method has some drawbacks, including having two representations for zero (+0 and -0) and complexities in arithmetic operations.
-
One's Complement: Positive numbers are represented as in sign and magnitude. Negative numbers are formed by inverting all the bits of the positive representation. For example, +5 would be 00000101, and -5 would be 11111010. This method still has two representations for zero.
-
Two's Complement: This is the most widely used method. Positive numbers are represented as in sign and magnitude. Negative numbers are formed by inverting all the bits of the positive representation and adding 1. For example, +5 would be 00000101. To get -5, invert the bits (11111010) and add 1, resulting in 11111011. Two's complement avoids the double-zero problem and simplifies arithmetic.
Example of Two's Complement (8-bit representation)
Decimal | Binary (Two's Complement) |
---|---|
5 | 00000101 |
-5 | 11111011 |
127 | 01111111 |
-128 | 10000000 |
0 | 00000000 |
In an n-bit two's complement system, the range of representable integers is -2(n-1) to 2(n-1) - 1.
Conclusion
Binary representation of integers is fundamental to how computers store and process numerical data. Different methods exist to represent both unsigned and signed integers, with two's complement being the prevalent choice for signed integer representation due to its efficiency and simplicity in arithmetic operations.