Search This Blog

Jul 21, 2011

Some interesting requirements

flipping bits(mirror)of an integer

For example, a = 00110101b, after flipping, b = 10101100b. When I saw this, the regular solution comes up at first time.
int reverse_bits(int input) {
    int result= 0;
    for (int i = 0; i < 32; ++i) {
        bit = input & 0x01;
        result |= bit;
        input >>= 1;
        result <<= 1;
    }
    return result;
}
It can match the requirement, however, it looks not best way to implement. So I checked from other talents from Internet. And then I got below: This one can shorten the loop count then first one.
unsigned long reverse_bits( unsigned long value )
{
  unsigned long result = 0;
  size_t n = NBITS( value );
 
  while (value)
  {
    result <<= 1;
    result += value & 1;
    value >>= 1;
    n--;
  }

  return result << n;
}
And I got another one below, it look more simple in code
#include 
#include 
 
#define NBITS(x) ( sizeof (x) * CHAR_BIT )
 
int reverse_bits ( unsigned value )
{
  unsigned int rv = value;
  size_t n = NBITS ( value ) - 1;
 
  while ( ( value >>= 1U ) != 0 ) {
    rv = ( rv << 1U ) | ( value & 1U );
    --n;
  }
  return rv << n;
}

No comments: