Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

2's Complement...

Status
Not open for further replies.

hughLg

Programmer
Feb 18, 2002
136
MY
In 2's complement calculation system, the most significant bit is used to identify if a number is positive or negative. "signed int" in C is for this purpose.

Currently, I haven't go further inside this feature in C yet. But i want to know, how can I identify a binary number is a positive number or negative? I know how to convert decimal number into binary even negative number. But after i got the result, if I act as another person that want to know if this number is positive number or negative, how can i do that? Stop talking about theory! Show you a example:

/* Example... */

Decimal Binary
---------------------------------------------
255 = 1111 1111 (as usual)

-255 = 1111 1111
= 0000 0000 (negate all bits)
+ 1
--------------------
0000 0001 (end result)

/* ...Example */

Since the '0' for most significant bit indicating positive number and '1' indicating negative number, but if I treat the end result shown above as positive number, it's wrong.

Anybody tell me more about these?...

Thanks for your attention.
 
You need 1 bit for the sign, so if you have 8 bits minus 1 for the sign, there are 7 bits left for the number. That means the range of 8 bits is from -128 to 127 and NOT from -255 to 255.

127 = 0111 1111
64 = 0100 0000
32 = 0010 0000
16 = 0001 0000
8 = 0000 1000
4 = 0000 0100
2 = 0000 0010
1 = 0000 0001
0 = 0000 0000
-1 = 1111 1111
-2 = 1111 1110
-4 = 1111 1100
-8 = 1111 1000
-16 = 1111 0000
-32 = 1110 0000
-64 = 1100 0000
-128 = 1000 0000

With 16 bits, the range is from -32768 to 32767,
32767 = 0111 1111 1111 1111
1 = 0000 0000 0000 0001
0 = 0000 0000 0000 0000
-1 = 1111 1111 1111 1111
-32768 = 1000 0000 0000 0000

etc.

Marcel

 
oh...i forget that -255 can only be expressed with higher bits...i just used 8 bits...

thanks a lot.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top