Convert decimal to signed binary

Say I want to convert "-128" to a binary file.

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

So 128 = 10,000,000

Thus, the "inverse" is 01111111

So, and "01111111" + "1" = "10000000", which is "-0", right?

It seems so easy in my textbook, but I can’t understand what I am doing wrong. Thanks for the help.

+4
source share
2 answers

No, it's definitely -128 (in any case, that's what you mean, given your description of negative numbers). This is only -0 for the sign / magnitude of negative numbers.

See this answer for details on the two views, plus a third that C allows, one addition, but I will copy the snippet from there to keep this answer as self-sufficient as possible.


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

  • invert all bits, then add one for two additions.
  • invert all bits for one addition.
  • inverts only the sign bit for the sign / value.

This can be seen in the following table:

 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 know that in 8-bit two add-on numbers there are no 128, the highest value is 127.

Where the numbers go at the midpoint where the smart happens:

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

because adding a bit pattern (e.g.) of 100 and -1 with 8-bit wrap will automatically give you 99 :

 100+ 0 0110 0100 1- 0 1111 1111 =========== 1 0110 0011 99+ (without that leading 1) 
+7
source

It depends on what your binary representation is: complement, complement, sign-magnitude, or something else. "Inverted bits and appendix 1" is true for two-component additions that most computers today use for extension numbers. In your example, β€œ10000000” is the 8-bit representation with two -128 additions you want. There is no such thing as -0 in the supplement.

For a signed value, you negate by flipping the sign bit. For one complement, you negate by inverting all bits.

+1
source

Source: https://habr.com/ru/post/1335927/


All Articles