Remix.run Logo
koakuma-chan 3 days ago

It just means the most significant bit represents the sign?

craftkiller 3 days ago | parent | next [-]

It's a little bit more complicated than that. If only the most significant bit represented the sign then you'd have both positive and negative zero (which is possible with floats), and you'd only be able to go from [-127 to 127]. Instead, it's some incantation where the MSB is the sign but then you flip all the bits and add 1. It is only relevant for signed integers, not unsigned integers.

pests 3 days ago | parent [-]

Ben Eater has a really good YT video on this.

lock1 3 days ago | parent | prev | next [-]

That's called "ones complement", the most significant bit represents a sign. Like the sibling post mentioned, it does have a weird quirk of having 2 representations for 0: (-0) and (+0).

While "twos complement" turns the MSB unsigned value to a negative instead of a positive. For example, 4-bit twos complement: 1000 represents -8 (in unsigned 4-bit, this supposed to be +8), 0100 represents 4, 0010 represents 2, 0001 represents 1. Some more numbers: 7 (0111), -7 (1001), 1 (0001), -1 (1111).

Intuitively, "ones complement" MSB represents a multiplication by (-1). While "twos complement" MSB adds (-N), with N = 2^(bit length - 1), in case of 4-bit twos complement it's (-2^3) or (-8). Both representation leave non-MSB bits work exactly like unsigned integer.

3 days ago | parent [-]
[deleted]
harpiaharpyja 3 days ago | parent | prev [-]

The other replies do a good job of explaining what 2s complement is.

I find the best way to understand why 2s complement is so desirable is to write down the entire number line for e.g. 3-bit integers.

Using 1s complement, the negative numbers are backwards. 2s complement fixes this, so that arithmetic works and you can do addition and subtraction without any extra steps.

(Remember that negative numbers are less than positive numbers, so the correct way to count them is:

-8 -7 -6 -5 -4 -3 -2 -1 0 +1 +2 +3 +4 +5 +6 +7

Where -1 is the largest possible negative number)