Signed Integers
Understanding Signed Integers
- Signed integers can represent both negative and positive numbers, including zero.
- In computing, signed integers are typically used when a variable could have a negative value.
- The highest bit (the sign bit) is used to denote whether the number is positive (0) or negative (1).
- Remainder of the bits then represent the magnitude of the number.
Binary Representation of Signed Integers
- In binary representation, positive numbers are denoted the same way as in unsigned binary.
- To represent negative numbers, two methods are commonly used: sign and magnitude and two’s complement.
Sign and Magnitude
- In sign and magnitude, the top bit (most significant bit) is used for the sign: 0 for positive, 1 for negative.
- The rest of the bits are used for the magnitude of the number.
- For instance, the number -7 would be represented in an 8-bit system as
10000111
.
Two’s Complement
- In the two’s complement method, the negative of a number is obtained by inverting all the bits of its binary representation and then adding 1 to the result.
- This system is commonly used as it simplifies the calculations for the computer, allowing addition and subtraction to be performed using the same circuitry.
- For instance, to represent -7 in an 8-bit system using two’s complement, we would flip the bits of 7 (
00000111
), getting11111000
, and then add 1, obtaining11111001
.
Bit Overflow and Underflow with Signed Integers
- Bit overflow occurs when an operation creates a number too large for the signed integer to represent, such as adding two large positive numbers together to result in a number that should be negative.
- Bit underflow occurs when a number is too small to be represented by the signed integer, such as subtracting a large positive number from a small positive number to result in a large positive number.
- Both situations create incorrect results and need to be managed within your programs.