-2

I've been trying to understand how negative numbers are notated in binary. As far as I understand, base on articles like this one:

Negative numbers: Two's complement

There is some math and reverting involved. My problem is that when I use online converters, and when I do the math by myself, to check the value of the binary code that these types of formulas give me, the result is never negative, but rather its own unique value positive.

It seems to me that the code itself is not negative, but rather the context tells you is negative.

I'd appreciate any help I can get since I am working on an exercise that is supposed to show the binary, octal and hexadecimal values of any int in C, and should be able to handle negative numbers, and I'm unsure how to handle negatives since adding a simple "-" before whatever notation seems rather underwhelming.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Luis Soto
  • 9
  • 2
  • A number is negative if it's first bit is `1`, on other words, if it was over half the max unsigned value – mousetail Jul 22 '22 at 12:58
  • I am not sure I understand. In the article it states that 1000 = -8, but to my understanding that actually = 8, positive. Now, I found another article that uses an extra bit, one that's 0 or 1, to sign it as positive or negative. https://www.geeksforgeeks.org/representation-of-negative-binary-numbers/ is that what you mean? – Luis Soto Jul 22 '22 at 13:09
  • If it's a 4 bit number, it will represent -7. If it's a 5 or more bit number, it will represent 8. – mousetail Jul 22 '22 at 13:10
  • @mousetail — `-7`? Surely `-8`? – Jonathan Leffler Jul 22 '22 at 13:20
  • @JonathanLeffler You are correct, the range is -8 to +7 – mousetail Jul 22 '22 at 13:21

1 Answers1

0

It depends on the interpretation of the bit pattern.

1000 has the decimal value of -8, if interpreted as 4 bit two's complement. Such a data type has a range from -8 to +7. All negative values have a most significant bit of 1, zero has all bits 0, and positive values have a most significant bit of 0.

1000 has the decimal value of (unsigned) 8, which you can consider positive, if interpreted as unsigned 4 bit. The range of such a data type is from 0 to 15.

If you take the same bit patterns and interpret them as the data types mentioned above, the decimal values from 0 to 7 have the same patterns, 0000 to 0111. The patterns 1000 to 1111 have different decimal values, for example 1100 is -4 as signed and 12 as unsigned.

the busybee
  • 10,755
  • 3
  • 13
  • 30