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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With