For example:
printf("%d", -1 & 3);
The output is 3. I tried with other number and it's the same. sorry for short question, but I don't think I should make it long for no reason.
I searched around and did not find answer to it.
For example:
printf("%d", -1 & 3);
The output is 3. I tried with other number and it's the same. sorry for short question, but I don't think I should make it long for no reason.
I searched around and did not find answer to it.
Some1) (not all) of the bitwise operators don't care about signedness of the operands but instead look at the raw binary representation of the variable.
In case of the negative value -1, the raw binary in the common two's complement format looks as 1111....1111
(all ones).
As an example, lets assume 16 bit int
, 2's complement:
Dec Bin
-1 1111 1111 1111 1111
3 0000 0000 0000 0011
-------------------------
& 0000 0000 0000 0011 = 3 dec
1) Specifically, & | ^ ~
and their compound assignment equivalents only look at the raw binary representation.
Because it is bitwise operation. Two complement's negative numbers have the most significant bit set, positive have this bit set to zero.
If you 1 & 0
the result will be always zero. So after this operation the MSB will be zero and the integer will be positive
Example (x - does not matter)
1xxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx
- negative number
0xxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx
- positive number
1xxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx
(negative) & 0xxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx
(positive) = 0xxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx
(positive)
Why "-1 & positive integer" always return the positive integer?
C allows various int
encodings. All have a sign bit. "There shall be exactly one sign bit." Only with that bit set may the value be negative.
Using &
will never set any bit including the sign bit. &
will only reduce - or keep the same - the bits that are set.
"anything & positive integer" will always result in a positive (non-negative) number.