Thursday, August 17, 2006

Bit masking

I was thinking of the hex to bin converter in the previous post. The fun part there was the extraction of the desired bit. With the knowledge in mind, it resulted me to devise a function in C that uses a mask to print out the bit representation of an integer.



void bitprint(int a)
{
int i;
int n = sizeof(int) * CHAR_BIT;
int mask = 1 << (n - 1);

for (i = 1; i <= n; ++i) {
putchar(((a & mask) == 0) ? '0' : '1');
a <<= 1;
if (i % CHAR_BIT == 0 && i < n)
putchar(' ');
}
}

CHAR_BIT is defined in limits.h and holding a value of 8. Try it, it’s fun. I’m bored, just extending my thanks to beandog for enlisting me in Planet Larry: Gentoo Users’ Blogs.

No comments: