I'm having a little difficult understanding how to work with bits in C, with regards to two's complement.
This is part of a homework assignment, but I'm not looking for a code answer, but rather to understand what's going on with two's complement representation.
My task is to restrict a number to a certain number of bits (n), and to determine whether or not a given number can be represented in two's complement in n number of bits.
According to examples, 5 CANNOT be represented as a 3-bit integer, while -4 CAN be represented as a 3-bit integer.
Why is this?
edit: I worked out a detailed explanation of my thought process, but realized I was completely off so decided to omit it.
My original reasoning was to see if it makes sense to allow 5 and -5, 4 and -4 to be represented in 3-bits. But that doesn't make sense because that doesn't really answer the problem.
I understand how 5 and -4 is represented as two's complement. Ex, as 4-bits:
5: 0101
-4: 1100
second edit:
For clarification, decided to add my original reasoning:
5 is 0101, and -5 is 1011.
I can see how 5 cannot be represented in two's complement when restricted to 3 bits, because without that 4th bit, we cannot indicate that -5 is a negative number. We need that extra 1 in 1011. If we could only have up to 3 bits, we'd have 011, and there'd be no way to differentiate -5 from 3, the latter of which is 0011 in 4 bits, and 011 in 3 bits.
Is this reasoning correct?
4 is 0100, and -4 is 1100.
Here I'm confused. I don't see why -4 can be represented in 3-bits as a two's complement integer.
4 is represented as 0100, and 100 with 3 bits. -4 is, if we start with 4 (100), we flip 100 (011), and add 1 (100), we are left with 100 again (in 3 bits). In 4 bits, I believe this is represented as 1100.
My confusion is, don't we need an extra 1, for 1100, to differentiate -4 from 4, which is 0100? If all we have is 3 bits, how can we differentiate 100 from 100?