2's complement is just adding a 1
to the 1's complement. Now, you are adding a binary bit 1 and not an int
1.
You will be storing the 2's complement in an int
. Just add another int
that contains binary 1. Getting two's complement is a little bit more involved. This involves bitwise addition. However, there is a trick to it that I had learned in highschool.
Consider the number six in binary as 0110
. The one's complement is 1001
. The two's complement is 1010
. The trick is this, find the right-most one. Having done that, flip the bits to the left of it, all the way to the end.
Use Integer.toBinaryString()
to see your answer.
To store a bit 1 in an int
, you'd do int bit = 0b0001
This will store a bit 1 in the lower-order bits of the int.
PS: I haven't made an SSCCE. Please correct me if I am wrong