Blog

[CS:APP 2.2] Binary Number Encoding

Published 1 min read

Unsigned

The formula for converting an unsigned, positive binary number to decimal is as follows.

It's easy enough to understand.

Signed

For signed binary numbers, you have to apply the following formula.

A rough proof

If we think about why this formula comes out,

below I matched up unsigned and signed for binary numbers where w is 3.

Unsigned

When 000 becomes 100, a 1 appears in the leading digit and 4 is added.

When 001 becomes 101, a 1 appears in the leading digit and 4 is added.

So, which is kind of obvious, the leading digit just plays the role of adding 4.

Signed

When 000 becomes 100, a 1 appears in the leading digit and -4 is added. When 001 becomes 101, a 1 appears in the leading digit and -4 is added.

So the leading digit plays the role of subtracting 4.

That's why in the formula above the leading digit is multiplied by a minus and added.

The relationship between Unsigned and Signed

If you use the formulas above and subtract B2T from B2U, you'll get that expression.

If we assume the leading bit is 1,

in other words, if we limit it to numbers that are positive in Unsigned and negative in Signed,

B2U - B2T = 2^w.

This relationship is useful when converting a Signed number to an Unsigned number or the other way around.

Comments

Leaving a comment stores your nickname (or GitHub profile info). Privacy policy

GitHub