Skip to content

Instantly share code, notes, and snippets.

@dariusk
Created January 12, 2016 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dariusk/505305e584bd8a2006f5 to your computer and use it in GitHub Desktop.
Save dariusk/505305e584bd8a2006f5 to your computer and use it in GitHub Desktop.
Brief description of signed integers for IntermezzOS book

Signed integers exist because we need some way to store negative numbers in a computer. Imagine you have 32 bits of storage and you want to put data in there. We could put in 0x00000001 and say that represents 1 in decimal, as you might expect. If we subtract 1 from that, we get 0x00000000, which represents 0. But if we subtract 1 from 0, the bits "wrap around" and we get 0xFFFFFFFF -- this happens on the hardware level! The internal counter has nowhere to go so it wraps around to the top of the range of representable bits.

If we'd been representing this number as an unsigned integer, 0xFFFFFFFF would represent 4,294,967,295. This is the number you'd normally expect if you started from 0x00000000 and kept counting up until you got to 0xFFFFFFFF. So when we have an unsigned integer, 0 - 1 = 4,294,967,295. Which is weird and probably not what we want! A signed integer is just a convention that reserves the top half of the 32-bit range (0x80000000 to 0xFFFFFFFF) to represent negative numbers, and it does it in backward order to make subtraction work out the way we'd expect. If we say that 0xFFFFFFFF represents -1, and 0xFFFFFFFE represents -2, etc., then suddenly our math looks good: 0 - 1 = -1.

Once consequence of this is that we're cutting the range of absolute values we can represent in half, so a 32-bit signed integer can only represent numbers between -2,147,483,648 and 2,147,483,647. This means if we tried to do 2,147,483,647 + 1 our result would be -2,147,483,648. That's an "integer overflow" error, and it's a problem because you normally assume that adding two positive numbers will result in an even larger number, but it's not true in this case and can cause major issues in your code. An "integer underflow" is the exact opposite: if we did -2,147,483,648 - 1 and got 2,147,483,647 as the result. Same error, just in the opposite direction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment