chewbacca
chewbacca

Reputation: 25

logical AND operation for two binary number in C

I should find result of "1001011 AND 1001010=1001010"...How can I find the result of this process in C programmin without using & symbol? Thanks for your help...

Upvotes: 0

Views: 248

Answers (2)

chqrlie
chqrlie

Reputation: 144951

You can perform this operation one bit at a time and get the result using the multiplication operator:

unsigned and(unsigned a, unsigned b) {
    unsigned mul = 1, res = 0;
    while ((a != 0) * (b != 0)) {
        res += mul * (a % 2) * (b % 2);
        a /= 2;
        b /= 2;
        mul *= 2;
    }
    return res;
}

For a more efficient approach, use the Boolean algebraic equivalence: Boolean equivalence

unsigned and(unsigned a, unsigned b) { return ~(~a | ~b); }

Upvotes: 1

Simon Willcocks
Simon Willcocks

Reputation: 328

This sounds a bit like homework, so...

The truth table for AND is:

0 AND 0 = 0
0 AND 1 = 0
1 AND 0 = 0
1 AND 1 = 1

The truth table for OR is:

0 OR  0 = 0
0 OR  1 = 1
1 OR  0 = 1
1 OR  1 = 1

What happens if you swap all the 0's and 1's in the bottom table?

NOT 0 OR NOT 0 = ?
NOT 0 OR NOT 1 = ?
NOT 1 OR NOT 0 = ?
NOT 1 OR NOT 1 = ?

I hope this helps, without giving the game away completely!

Upvotes: 0

Related Questions