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.
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-0for 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:
You can see this in the table below:
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:
because adding the bit pattern of (for example)
100and-1with an 8-bit wrap-around will auto-magically give you99: