Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting decimal to signed binary

Tags:

binary

Let's say I want to convert "-128" into binary.

From what I understand, I get the binary representation of "128", invert the bits and then add 1.

So 128 = 10000000

So the "inverse" is 01111111

So and "01111111" + "1" = "10000000" which is "-0" isn't it?

My textbook makes this seem so easy but I can't figure out what I'm doing wrong. Thanks for the help.

like image 872
Michael Avatar asked Jan 18 '11 03:01

Michael


People also ask

How do you convert .75 to binary?

Therefore, the binary equivalent of decimal number 75 is 1001011.


2 Answers

No, that's definitely -128 (in two's complement anyway, which is what you're talking about given your description of negating numbers). It's only -0 for the sign/magnitude representation of negative numbers.

See this answer for details on the two representations plus the third one that C allows, one's complement, but I'll copy a snippet from there to keep this answer as self-contained as possible.


To get the negative representation for a positive number, you:

  • invert all bits then add one for two's complement.
  • invert all bits for one's complement.
  • invert just the sign bit for sign/magnitude.

You can see this in the table below:

number | twos complement     | ones complement     | sign/magnitude
=======|=====================|=====================|====================
     5 | 0000 0000 0000 0101 | 0000 0000 0000 0101 | 0000 0000 0000 0101
    -5 | 1111 1111 1111 1011 | 1111 1111 1111 1010 | 1000 0000 0000 0101

You should be aware that there is no 128 in 8-bit two's complement numbers, the largest value is 127.

Where the numbers pass the midpoint is where the "clever" stuff happens:

00000000 ->    0
00000001 ->    1
: :
01111110 ->  126
01111111 ->  127
10000000 -> -128
10000001 -> -127
: :
11111110 ->   -2
11111111 ->   -1

because adding the bit pattern of (for example) 100 and -1 with an 8-bit wrap-around will auto-magically give you 99:

100+  0 0110 0100
  1-  0 1111 1111
      ===========
      1 0110 0011  99+ (without that leading 1)
like image 78
paxdiablo Avatar answered Jan 01 '23 14:01

paxdiablo


It depends on what your binary representation is -- ones complement, twos complement, sign-magnitude, or something else. The "invert bits and add 1" is correct for twos complement, which is what most computers these days use internally for signed numbers. In your example, "10000000" is the 8-bit twos-complement representation of -128, which is what you want. There is no such thing as -0 in twos complement.

For sign-magnitude, you negate by flipping the sign bit. For ones complement, you negate by inverting all bits.

like image 20
Chris Dodd Avatar answered Jan 01 '23 14:01

Chris Dodd