Digital Stronghold - Software Engineering, Musicality and Facts of Life…



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.

1 Comment »

The URI to TrackBack this entry is: http://eradicus.blogsome.com/2006/08/17/bit-masking/trackback/

  1. teach me puhhleeezzzeeee! =) you’re my idol!

    Comment by unknown — August 20, 2006 @ 4:54 am

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.

Theme designed by Joset Anthony Zamora


Digital Stronghold

↑ Get Headline Animator