开发者

Getting Lower-Order N Bits

Is there any way you can get any integer's lower-order n bits (where n can be any number betwe开发者_高级运维en 1 and 32) without previously pre-computing 32 bitmasks, one for each order, and using the & operator? I also don't want to be using % with powers of two, just bitwise operations.

Edit: Say, for example, that a user enters an integer Num and another integer ShiftCount with a value ranging from 1 to 32. I want to store in a third variable the bits that are lost in the operation Num >> ShiftCount.


Something like Num & ((1 << ShiftCount) - 1)?


How about this solution? It's strictly bit-twiddling—no math required:

public static int LowOrderBits( int value , int bits )
{
  if ( bits < 0 || bits > 32 ) throw new ArgumentOutOfRangeException("bits") ;
  return (int) ( ((uint)value) & ~(0xFFFFFFFF << bits) ) ;
}

@jdv-Jan de Van's solution requires subtraction, as does @Mark Sowul's (to obtain a value for n:

public static int LowOrderBits( int value , int bits )
{
  if ( bits < 0 || bits > 32 ) throw new ArgumentOutOfRangeException("bits") ;
  return (int) ( ((uint)value) & (0xFFFFFFFF >> (32-bits) ) ) ;
}

Subtraction is probably a more expensive operation than simple bit operations.


How about starting with 1111...1111 (UInt32.MinValue), right-shifting it n bits (make sure to use uint so it doesn't sign-extend!), and then &-ing it with the value for which you want the lower-order bits?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜