Friday, February 26, 2010

The number that wasn't

Signed numbers on computers are handled in a special way. Computers deal with bits (1s and 0s). Numbers are represented using a number of bits, usually 8, 16, 32. To represent a signed number one of the bits is used to tell if its positive or negative, usually the 1st bit. Usually this all works and everything goes well. Sometimes you want a number using a different number of bits, like 3, 4, or 5. Some languages allow you to do this automatically. In C this would look like

struct {
int foo : 5
int bar : 1
} my_number

This makes foo 5 bits and bar 1 bit. Both of these are defined as signed numbers. foo can represent a number from -16 to 15. The question now is what values can bar hold? Because it is signed, the 1st bit will be used to tell if its negative or positive. There are no bits left to tell what the value will be. So what values can it hold? If you were wondering it is possible to define a number in your program like this.

No comments:

Post a Comment