#CS250#Information#Computer-Science
- There are a lot of ways to represent numbers as bit strings, here’s just a few common ones
Unsigned Integer Representation
- Used to represent positive integers and pointers in C
-
of and weights of positions fully defines the scheme
- If the least significant bit is 0, the number is even
- If least two significant bits are 0, it’s a multiple of 4
- Unsigned integer is basically just take the bit string as a binary number representing a decimal number
- Just convert it straight from decimal to binary
Sign Magnitude Integer Representation
- Leftmost bit represents the sign of the number. 0 = positive, 1 = negative
- Rest of bits are the magnitude ()
- You can have both positive and negative numbers with this representation
- Weird quirk you can have positive 0 and negative 0, because
- 00000000 = +0
- 10000000 = -0
- Good things
- Negation is easy (just invert the sign bit)
- Absolute value is easy (set sign bit to 0)
- Convert to larger number of bits easily (put a bunch of 0’s between sign and magnitude)
- Bad things
- Compare(A,B) is HARD
- -0 = +0, so negative isn’t always less than positive
- Addition and subtraction is HARD
- Requires comparison of magnitudes to find new signs and thus more complex circuits
- Compare(A,B) is HARD
2’s Complement Integer Representation
- Values are the same as in unsigned integer, but the most significant bit (furthest left) is negative
- Good things
- Adding and subtracting works properly still
- This means you can use the same circuit for both unsigned and 2’s complement arithmetic!
- Only one representation of 0
- Most significant bit is not just a sign, but it can be interpreted as such; MSB is an implicit sign bit
- Absolute(max neg value) = Abs(max pos val + 1)
- Adding and subtracting works properly still
- Bad things
- Inverting bit strings is a lot harder
- To invert, invert each bit within the string (1 -> 0 and 0 -> 1) and add 1 to it to get the opposite value
- Inverting bit strings is a lot harder
Int Representations in Computers Today
- Unsigned and 2’s complement are built in to all modern computers
Casting
- When we cast, we just fill in the extra bits with
- Same values as sign bit in 2’s complement
- 0’s in unsigned integer representation
- Compilers have to be careful not to cast things with wrong wires in hardware
- Source code has to take care to not cast to fewer bits
Overflow
- Overflow is when the resulting number of bits from an operation is too large for the given representation