Reputation: 2075
Going through the book "Cracking the coding interview" by Gayle Laakmann McDowell, in bit manipulation chapter, it posts a question:
Find the value of (assuming numbers are represented by 4 bits):
1011 & (~0 << 2)
Now, ~0 = 1 and shifting it two times towards the left yields 100 ( = 0100 to complete the 4 bits). Anding 1011 with 0100 equals 0000.
However, the answer i have is 1000.
Upvotes: 0
Views: 2011
Reputation: 96810
1011 & (~0 << 2)
~0
is not 1 but rather 1111
2 or 0xF
16.1111
to the left twice gives 1100
(the two leftmost bits have been dropped and filled in with 0s from the right).1011 & 1100
gives 1 in each bit position for which the corresponding bit position is 1, otherwise 0. This follows that the result is 1000
.Upvotes: 2
Reputation:
~0
is not 1 but 1111
(or 0xf
). The ~
operator is a bitwise NOT operator, and not a logical one (which would be !
).
So, when shifted by 2 places to the left, the last four bits are 1100
. And 1100 & 1011
is exaclty 1000
.
Upvotes: 8
Reputation: 49372
~
is the Bitwise Complement Operator.
The value of ~0
should be 1111
in 4 bits .
1011 & (~0 << 2)
= 1011 & ( 1111 << 2)
= 1011 & 1100
= 1000
Upvotes: 2
Reputation: 7160
~0
does not equal 1. The 0
will default to being an integer, and the NOT operation will reverse ALL the bits, not just the first.
Upvotes: 2