Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 between 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.

like image 242
Miguel Avatar asked May 08 '26 21:05

Miguel


2 Answers

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.

like image 40
Nicholas Carey Avatar answered May 11 '26 11:05

Nicholas Carey