Popular Posts

Thursday, July 16, 2009

Common Binary Data Operations with C..

Common Binary Data Operations with C

Now that you know how to compile and link your programs, let's dive into the magic world of bitwise operations. At first these might seem really confusing, but you will notice that you have in fact seen all of them during Computer Engineering.

Shift Operations

It might seem a bit more cryptic than the first example, but don't be frightened. What you see is the usual stdio.h which is included at the beginning and then a function called getbinarystring. Skip it over and move on to the main function, which introduces two consecutive loops right after a block that handles command line processing.

The binary shift operator in C is a double-less-than or a double-greater-than character. Less-than means shifting to the left and greater-than the opposite. In effect, binary shifting is actually multiplying or dividing by powers of two. So, if you wish to divide a value by four, you shift the bits to the right by two:

value = value >> 2;

... Or if you want to multiply by 8:

value = value <<>

Of course, you need to know that overflows are not prohibited and you might send your MSB:s to bit heaven!

Bitwise AND

You can use two notations to perform bitwise and-operations:

result = op1 & op2;

.. or ..

result &= op;

which is equal to

result = result & op;

Experiment with the code in file and.c.

Bitwise OR


The notation of OR is similar to AND in C, but the operator character is a pipe character:

result = op1 | op2;

Again, there is a code snippet in file or.c that should clarify the usage of OR operator.

Bitwise XOR


Have a look at file xor.c and see that the XOR operation is nothing special, except for the operator character in C, a caret: ^.

No comments: