I was thinking about ints and shorts now in C#. Shorts in C# can hold values from -32768 to 32767. I know that other languages do this the other way round -32767 to 32768. I was wondering why either the negative or positive has one extra digit. I did study and understand this but it was 20 years ago and I have forgot and can't figure it out. If we have 16 bits and one of them is used to indicate whether the number is negative or positive then the remaining bits can therefore hold values from 0 to 32767.

I knocked a little spreadsheet together to illustrate this and tinker with but I can't figure out why either negative or positive numbers have one extra digit. Clearly there is a good reason - it just escapes me at the moment. If you want to look at my spread sheet you can get it at:

http://www.dacservices.co.uk/ee/binary.xls

Thanks

Dave

I knocked a little spreadsheet together to illustrate this and tinker with but I can't figure out why either negative or positive numbers have one extra digit. Clearly there is a good reason - it just escapes me at the moment. If you want to look at my spread sheet you can get it at:

http://www.dacservices.co.uk/ee/binary.xls

Thanks

Dave

Do more with

EXPERT OFFICE^{®} is a registered trademark of EXPERTS EXCHANGE^{®}

Lets simplify this by looking at TinyInts instead of ints and shorts.

The Byte type takes numbers from 0 to 255. But lets use the same byte to represent both positive and negatives

A byte can hold a total of 256 numbers. This includes the number zero.

Hence there are 255 left. Either 128 positive and 127 negative, or 128 negative and 127 positive.

A similar explanation goes for shorts and ints

Regards,

Dabas

The reasoning is as follows.

In signed binary, an integer goes from 32767 to - 32768 because it has 2 bytes assigned in memory.

each byte is 8 bits so it has a total of 16 bits in memory. Imagine each bit as a box that fits one entry.

In binary the first box from the left is assigned for + or - for signed integers like the one your asking about.

Which leaves only 15 boxes to work with for the numbers.

+32767 in binary is:

0111111111111111 (0 and 15 ones)

-32768 in binary is:

1000000000000000 (1 and 15 zeros)

In signed integers, the leftmost bit is used to indicate the sign. if the first of the 16 bits is a zero then it's positive. If the sign bit is set (=1), then the number is negative. Since one bit is used for the sign, then there are only 15 bits to work with.

1111111111111111 (16 ones) is actually -1 in decimal, hint they start backwards and they can end with (one and 15 zeros) while the positive has to end with (zero and 15 ones) to keep the first bit a zero.

hope this makes a little more sense.

## Premium Content

You need an Expert Office subscription to comment.Start Free Trial