Not logged in, Join Here! or Log In Below:  
 
News Articles Search    
 

 Home / General Programming / one_bit_set Account Manager
 
Archive Notice: This thread is old and no longer active. It is here for reference purposes. This thread was created on an older version of the flipcode forums, before the site closed in 2005. Please keep that in mind as you view this thread, as many of the topics and opinions may be outdated.
 
Foddex

May 13, 2005, 11:30 AM

I just had the need for code that checks if for a given unsigned int only one bit is set. This is valid for a limited set only (1, 2, 4, 8, 16, etc.)

But what code would you write to determine this? I came up with two totally different solutions, but I was wondering what other programmers would come up with (maybe obvious, way better solutions?). Also wonder what the fastest way is :)

  1.  
  2. // Listing 1, shift right until a bit falls off
  3. // if it does, the remainder must be 0
  4. bool one_bit_set( unsigned int v ) {
  5.   if (!value) return false;
  6.   unsigned int o = v;
  7.   while (v && v==o) v>>=1;
  8.   return !v;
  9. }
  10.  


  1.  
  2. // Listing 2, switch
  3. switch (v) {
  4.   case 1:
  5.   case 2:
  6.   case 4:
  7.     ...
  8.   case 2147483648:
  9.      return true;
  10.   return false;
  11. }
  12.  

 
Steven Hansen

May 13, 2005, 11:35 AM

This is equivalent to checking for power of 2. A nice simple solution exists.

  1.  
  2. BOOL isPow2(unsigned int x) {
  3.    return (!(x & (x - 1)));
  4. }
  5.  

 
This thread contains 2 messages.
 
 
Hosting by Solid Eight Studios, maker of PhotoTangler Collage Maker.