C - Binary - Operation with decimals

A good way to understand binary operations is to play with decimals.
What?!

Yes, if you can manipulate decimals like binaries, then you can say "OK! I've understood how binary works".

Let's check this with this binary-operation tutorial with decimal numbers.

Explanation

In the code below I'm starting with a XOR operation.
I'm doing number XOR mask.
number = 4.
mask = 7.

And the result is 3.

What happened exactly?

Actually, we have to transform those decimal numbers into binary.
So, 4 in decimal is equal to 100 in binary.
And 7 is equal to 111.

  • 4 = 100.
  • 7 = 111.

With the XOR operator I'm able to remove each comparaison equal in both numbers. It's a classic XOR.
So we can see below this operation.

 100
^111
 ---
=011
  • 1 XOR 1 = 0.
  • 0 XOR 1 = 1.
  • 0 XOR 1 = 1.

Done! We have now our result.

011 in binary is equal to 3 in decimal.
 

Using the bitwise complement, or the tilde (~) operator

Now we can play with the ~ operator to achieve a different result.

If we applied the ~ operator on our result, we would have the opposite number in binary.

For example, if the result was 7 in decimal (111 in binary), its oppsosite would be -8 (1000 in binary).

And if we took -8, its opposite would be 7.
If we took 8, its opposite would be -9.

Code

#include <stdio.h>

void binaryMe() {
    int number = 4;
    int mask = 7;
    int mask15 = 15;
    int result = 0;

    printf("Number = %d\n", number);
    printf("mask = %d\n", mask);


    result = number ^ mask;
    printf("result XOR = %d\n", result);

    result = number & mask;
    printf("result AND = %d\n", result);

    result = number | mask;
    printf("result OR = %d\n", result);

    result = ~result;
    printf("~result = %d\n", result);

    result = ~result;
    printf("~result = %d\n", result);

    result &= number;
    printf("result &= number -> %d\n", result);

    result ^= mask15;
    printf("result |= number -> %d\n", result);

    printf("~-8 = %d\n", ~(-8));
}

int main() {
    binaryMe();
    return 0;
}

Compiling, running

gcc main.c -o myBinary ; ./myBinary

Result

Number = 4
mask = 7
result XOR = 3
result AND = 4
result OR = 7
~result = -8
~result = 7
result &= number -> 4
result |= number -> 11
~-8 = 7

Conclusion

A great exercice to train yourself to understand binary operations.
Good job, you've made it. wink

Comments

Comment: 

result|=number--> 4 as result is 4 now and anding with number=4 is equal to 4

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.