Cisco Systems Interview Question
logically ok.
karate, by the time the control reaches the second part of the logic x has already been shifted left so right shifting puts it back to its original position with the left most bit missed, possibly. as i know the shifting works in place, so the best option would be to use this way
a = x
left = x<<1 & 0b10101010
right = a>>1 & 0b01010101
x= left | right
@amazonianMonkey
Your logic is not correct, you don't need to shift it back because the send shift is performed on the original x value.
Consider,
int x = 2;
x = x << 1 | x << 1;
if you look at the assembly, assuming %eax has x
add %eax %eax
or %eax %eax
If you print out x, the output is 4 not 12.
@gus
so you mean to say in case of your solution by the time control reaches the second part (the second part of OR) the value of x is the same as the original, right?
((x<<1)&(0b10101010)) |(x&0b01010101)
i don't think so! How do you explain that...this logic applies to post/pre increment operators in C/C++, but how do you apply the same here, can you write concrete examples? would be nice to make things clear for my understanding. Thank
#define ENDSWAP2BITS(x) ((((x)&0x03)<<2)|(((x)&0x0c)>>2)|(((x)&0x30)<<2)|(((x)&0xc0)>>2))
int x= ( (x & 0xAAAAAAAA)>>1 | (x & 0x55555555)<<1 );
- Anonymous August 23, 2009