Monthly Archives: October 2013

Bitwise Cheat sheet

The problem

I have lived long enough to see lots of code. and I usually find that if you force a developer to do some bit manipulation, he will write very complicated, very hard to read, and usually WRONG code. for example:

 

// check if a window is not minimized and not hidden:

isDialog = (WndStyle & (~IS_VISIBLE) &&  (WndStyle & (~IS_MIN))

 

Who should read this?

I work in a company where we deal a lot with FileSystems, and their APIs tend to overuse Flags. Lots of Access Masks and ACLs etc. So I am often faced with a situation where I need to do extensive bit-manipulation.

Here I tried to collect all the tricky bitwise operations you will need to do if you are a normal developer, a young geek. Those working on Cryptology or Networks, are major geeks, and, will need a more comprehensive list of operations than this one. I suggest you check Hacker’s Delight

Another smart idea is to collect all these operations in a header file like bithacks.h

Who can read this?

I assume you are already familiar with basic bitwise operations. If you are not sure if you need to read this article, answer the following question. If you can’t, then this article is not for you.

What is the difference between Bitwise AND &,and Logical AND &&?

 

Conventions

I use the C language Bitwise operators, they are almost the same in every other language I used except Assembly

AND

&

OR

|

XOR

^

NOT

~

Shift Left

<<

Shift Right

>>

Flags:

Check if a flag is set

#define  VISIBLE  0x01

isVisible = var & VISIBLE 

Complex Flags

Some times a flag is more complex, a set of different flags:

#define  VISIBLE  0x011C00

isVisible = (var & VISIBLE) == FLAGX

Check if a flag is not set

isHidden = Var & (~VISIBLE)

 

Test if n-th bit is set

isSet = (x & (1<<n))

Arithmetic

Check if an integer is odd:

isOdd = (Var & 1);

 

Print a variable in Hexadecimal:

int var = 0xcf14L;

printf(“0x%.8X”, Var);

outputs: 0x0000CF14

 

Characters

 

to Lowercase

OR with a space ‘ ‘. Works even if the letter is already lowercase. check an ASCII chart to understand why.

‘a’ == (‘A’ | ‘ ‘)

to Uppercase

Remove the space bits. or AND by an underline ‘_’.

‘A’ == (‘a’ & ~’ ‘)

‘A’ == (‘a’ | ‘_’)

 

Invert Case (lower to upper, upper to lower)

Flip the space bits. Flip means XOR

‘A’ == (‘a’ ^ ‘ ‘)

‘a’ == (‘A’ ^ ‘ ‘)

 

These are the basics. let me know if you have some tricks up your sleeves…