Thursday, October 11, 2007

Bit Twiddling

Okay, so I have this problem... I want to do something like:

if(a == 0){
a = b;
}

where a is a positive integer.

But without using an "if" (branching code really sucks). I found this crazy page and adopted it to my needs.

Here's my solution:

#include <stdio.h>

int main(){
unsigned int a = 0;
unsigned int test_msb = -a;
unsigned int mask = (unsigned int) (((int) test_msb)>>31);
unsigned int c = 2;

int result = (int) (a & mask)|(c & ~mask);
printf("%x %d\n", mask, result);
return 1;
}

If I change a to another positive integer, a is printed. When a is 0 (as is hardcoded above -- kids, don't try this at home), c (i.e., 2) is printed. Wee-hoo.

No comments: