Basic Bit Operations

In low-level programming, there are times when you need to set, clear, toggle or check a single bit of a given variable. And, in my case, there are an equal number of times I just can’t remember how to do so!  Instead of repeatedly resolving into Stackoverflow I thought I’d write the tricks right here for future reference.

The bitwise operators & (AND), | (OR), ^ (XOR), ~ (NOT), << (L SHIFT) and >> (R SHIFT) work basically the same in every programming language: I usually come across these problems when writing low-level code in C.

OK, on with the tricks already!

Set bit x of variable num
num |= 1 << x;

Clear bit x of variable num
num &= ~(1 << x);

Toggle bit x of variable num
num ^= 1 << x;

Check value of bit x in variable num
value = (num >> x) & 1;

The last one returns a nonzero value if the bit is set (the value may not be exactly 1), zero otherwise.

And there you have it!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: