-3
void main() 
{ 
int x=7; 
printf("%d",x&(x-1));
int y=6; 
printf("%d",y&(y-1)); 
printf("%d",y>>2); 


}

When I put an odd number I get output n-1 where n is a odd number but when i put y= even number I get output 0.I am not able to understand this please help.

My second question is that when i print y>>2 that is 6>>2 I get ouput 1.Please explain me this also. I know these are bitwise operations but my concept is not clear.Thanks

  • 4
    http://en.wikipedia.org/wiki/Bitwise_operations_in_C - grab a paper and a pen(cil) and work it out. –  Aug 12 '13 at 17:44
  • 1
    Also, `(x & (x-1)) == 0` can be used to checks if `x` is a power of 2 (or 0) – P0W Aug 12 '13 at 17:48

3 Answers3

0

Let's break each line up:

x&(x-1) => 0x111 & 0x110 => 0x110 => 6

... and:

y&(y-1)) => ox110 & 0x101 => 0x100 => 4

... and finally:

y>>2 => 0x110 >> 2 => 0x001 => 1

Remark: It's probably a good idea to review your knowledge of bitwise operations.

Jacob Pollack
  • 3,703
  • 1
  • 17
  • 39
0

Bitwise operations are exactly that. you take your number and you and each bit with the other number.

What that means, is if both numbers have a 1 at the slot, than you output 1, else, you output 0

so, for your example of 7 you have

0111
0110

result:

0110 (6)

for your example of 6 you have

0110
0101

result:

0100 (4)

right shift (>>) just shifts all the bits to the right, so if you take 6

0110

and shift all the bits to the right twice, you end up with

0001

or 1

0

When I put an odd number I get output n-1 where n is a odd number but when i put y= even number I get output 0.I am not able to understand this please help.

With binary storage the lowest bit is always 1 for odd numbers, but since you are ANDing, you are in effect simply returning the original value-1 always (because no bits have shifted). In the case of even numbers not all of the will be 0: 8 will: 1000 & 0111 = 0. 6 will not: 0110 & 0101 => 0100 = 4.

My second question is that when i print y>>2 that is 6>>2 I get ouput 1.Please explain me >>this also. I know these are bitwise operations but my concept is not clear.Thanks

It like dividing by 2 twice. so 6->3->1.5 But the fraction part is truncated, so you are left with 1. In binary, this would be 0110 -> 0011 -> 001.1 = 1.5 (decimal) but with truncation = 0001.

Jiminion
  • 5,080
  • 1
  • 31
  • 54