views:

106

answers:

2

This is a follow on question from my previously answered question here:

http://stackoverflow.com/questions/2185719/reading-characters-on-a-bit-level

The problem that I seem to be having is understanding the basic concepts of bit manipulation in C. I understand what needs to be done but I am having trouble actually developing a solution to it.

An example:

Changing 01101010 to 00111110 using a logical operator.

I understand the principle and the need of a mask to implement the solution but I don't understand how to do it programatically.

I come from a heavily based C# background and have only recently begun developing in C.

Can anyone give me some pointers or tips to complete the example?

Following is the solution incase anybody else finds it useful:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h.>

int main()
{
    //01101010 - 106 Decimal
    char a = 0x6A;

    //01010100 - 84 Decimal
    char b = 0x54;

    //00111110 - Uses exclusive or (XOR)
    char c = a ^ b;

    //Prints out in Hex - 62 Decimal
    printf("%x",c);

    return 0;
}
+2  A: 

You can XOR those together. The XOR of two bits is 1 if exactly one of the bits is 1.

    01101010
XOR 00111110
=
    01010100

XORing the first value with this result will give you the second.

    01101010
XOR 01010100
=   00111110

In C:

char a = 0x6A;
char b = 0x3E;
char c = a ^ b;

(c ^ a == a ^ b ^ a) && (a ^ b ^ a == b)
Matthew Flaschen
Jamie Keeling
There's no real purpose. It's just a (valid C) true expression to demonstrate the syntax and recap what we've done.
Matthew Flaschen
Thank you for the answer.
Jamie Keeling
+1  A: 

I'd proceed like this: First look at which bits need to change. If you only need to change 1s to 0s, you want &. If you only need to change 0s to 1s, you want |. If you need to change in both directions, like is the case here, you want ^ because it's the only operator that can go both ways, so to speak.

Now it's just a matter of finding the right bit mask to xor with. Since 1^0=1 and 0^0=0, you have to set the bits that you don't want to change to 0 in the bitmask. Set the others to 1 (1^1 is 0 and 0^1 is 1) and you'll get the result you want.

sepp2k
Thank you for the guidance.
Jamie Keeling