Signed and Unsigned Numbers

How computers represent numbers

Rukshani Athapathu
Coder's Corner
4 min readMay 11, 2018

--

Computers use binary digits ( or in other words bits) to store and process information. A binary digit can be of one of the two values, 0 or 1.

For example, take the decimal number 59. Binary form of that decimal number 59 is 111011.

Word

Computer word is a unit of data with a defined bit length that a CPU can process at one go. In recent years, many machines have shifted from 32 bit word sizes to 64 bit word sizes.

Let’s represent 111011 as a 32 bit word.

Here the right most bit is called least significant bit and the left most bit, the most significant bit. With 32 bits, we have 2³² bit patterns which means we can represent numbers from 0 to 2³²-1 (4,294,967,295).

Computer programs use both the positive and negative numbers, so now we need a way to differentiate negatives from positives.

Unsigned encoding

If we assume that we have 32 bits, then with unsigned encoding every number between 0 and 2³² -1 has a unique encoding. That is each number in this range will map to a unique bit pattern.

With w bits, number range is,

Two’s complement encoding for signed numbers

To represent negative values, most computers use two’s complement encoding. With this encoding, most significant bit has a negative weight. So all negative numbers will have 1 in the most significant bit which is also known as the sign bit. Therefore, when the sign bit is 1 the value is negative and when it is 0 the value is positive.

For example, if we take the binary number 1011 which is a 4 bit word, now with two’s complement, its value can be calculated as follows,

With w bits, number range is,

  • Minimum Value
  • Maximum value (Sign bit 0 and all the other bits set to 1)

Zero extension

To convert an unsigned number with w-bits to a number with more than w bits, we simply add 0s to the left. Let’s say we have a 16-bit unsigned number and we want to convert this to a 32-bit number, we simply fill the leading 16 bits with 0s. This is called zero extension.

  • 16-bit Version
  • 32-bit Version

Sign extension

To convert a two’s complement number with w bits, to a word which has more than w bits, we can use sign extension.

For example, let’s say we have number -4 in a 16 bit word and we want to convert this to a 32-bit word.

[Shortcut to negate a two’s complement number is to invert every 0 to 1 and every 1 to 0, and then add one to the result.]

Now to convert this 16-bit version of -4 to a 32-bit version, we simply copy the sign bit 16 times on to the left.

Well, that’s it!

References

--

--