Clear all but least signficant n bits of x

深入理解计算机系统 68

  /*Clear all but least signficant n bits of x

*Examples: x = 0x78ABCDEF,n = ->0xEF,n = 16 ->0xCDEF

*Assume 1 <= n <= w(w = 32)

*/

int lower_bits(int x,int n);


实现代码如下:

int lower_bits(int x,int n){

int  y = (~0<<(n-1))^(-1);
 y = (y <<1)|0x1;

 return x&y;

}

你可能感兴趣的:(深入理解计算机系统,;位级运算)