Those old C bit tricks

After spending a lot of years writing C code it is sometimes hard to get some of those "tricks" out of your mind. The thing I always felt about C was it seemed to encourage you figure out or use cool tricks. Couple that with graphics coding you can get some strange stuff like the infamous 0×5f3759df q_sqrt function. Even though some of them are fairly worthless in modern computing, they are fun to look at and think about why they work!

I was feeling nostalgic and was going through old code and bookmarks and here are some of the more simpler ones. These are all pretty well known, so I make zero claims of authorship. :) On non-32 bit architectures, your mileage may vary.

The swap two values without using extra variables trick.

This is probably the most famous. The one most people get handed to them in an intro level CS class by that devious TA. Given two unsigned int variables, swap their values without using any additional variables.

  1. uint x = 100;
  2. uint y = 322;
  3. System.Console.WriteLine(x + " " + y); // prints 100 322
  4. x ^= y;
  5. y ^= x;
  6. x ^= y;
  7. System.Console.WriteLine(x + " " + y); // prints 322 100

Test if a number is a power of 2

  1. uint x = 256;
  2. System.Console.WriteLine((x & (x - 1)) == 0); // prints true
  3. x = 13
  4. System.Console.WriteLine((x & (x - 1)) == 0); // prints false

Next largest power of 2

  1. uint x;
  2. x = 156;
  3. x |= (x>> 1);
  4. x |= (x>> 2);
  5. x |= (x>> 4);
  6. x |= (x>> 8);
  7. x |= (x>> 16);
  8. x++;
  9. System.Console.WriteLine(x); // prints 256

Got a lot of mileage out of this in the days when OpenGL texture maps had to be powers of 2.

Odd or even test

  1. uint x = 101;
  2. System.Console.WriteLine((x & 1) == 0); // prints true (is odd)
  3. x = 100;
  4. System.Console.WriteLine((x & 1) == 0); // prints false (is even)

Or, you can test against modulus 2 and invert the results (false is odd, true is even).

There best source for this kind of stuff is The Aggregate Magic Algorithms.

kick it on DotNetKicks.com

One Response to “Those old C bit tricks”

  1. DotNetKicks.com Says:

    Those old C bit tricks…

    You’ve been kicked (a good thing) - Trackback from DotNetKicks.com…

Leave a Reply