user720694
user720694

Reputation: 2075

Bit manipulation (clear n bits)

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

Answers (4)

David G
David G

Reputation: 96810

1011 & (~0 << 2)
  1. ~0 is not 1 but rather 11112 or 0xF16.
  2. Shifting 1111 to the left twice gives 1100 (the two leftmost bits have been dropped and filled in with 0s from the right).
  3. Adding 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

user529758
user529758

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

AllTooSir
AllTooSir

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

Matt
Matt

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

Related Questions