0

这个函数有什么作用,因为我无法弄清楚它的目的。

int f( int n, int l, int r )  
{  
return (n << l) >> r;  
}  
4

2 回答 2

4

它向左移动 nl 位,然后向右移动 r 位

它有效地乘以 2^l 然后除以 2^r

或者换一种说法,它将低位(lr)位清零。

于 2012-06-26T15:29:05.493 回答
1

I always approach these by doing an experiment with smaller numbers and thinking in binary. E.g. let's make them unsigned 8-bit values first. Let n be 0xFF (255), l be 3, r be 2.

So it's 2 steps (cha-cha). First step we shift left l bits.

1111 1111b << 3 == 1111 1000b == 0xF8 == 248

Then we shift the result right r bits:

1111 1000b >> 2 == 0011 1110b == 0x3E == 62

Now as @wildplasser noted, your values are signed, so instead of shifting in 0's, you'll be sign-extended. So let's assume 8-bit signed values. Let n be 0xFF again, (-1) in decimal.

The left shift remains the same, but when you right shift, the sign bit will be extended.

1111 1111b << 3 == 1111 1000b == 0xF8 == -8
1111 1000b >> 2 == 1111 1110b == 0xFE == -2

So I'm not sure what the intention of the function is, but at least I understand what it does. If this is some standard idiom for doing something, I don't know what it is.

于 2012-06-26T15:46:34.790 回答