David Ranieri
David Ranieri

Reputation: 41017

Bitwise excluding values

How to

if (x == 1) printf("2\n");
else if (x == 2) printf("1\n");
else printf("0\n");

using bitwise operators?

My attempt is:

for (x = 0; x < 8; x++) {
    printf("%d\n",  0x03 & (0x03 ^ x));
}

Output:

3
2
1
0
3
2
1
0

Desired output:

0
2
1
0
0
0
0
0

Upvotes: 5

Views: 635

Answers (5)

Falk H&#252;ffner
Falk H&#252;ffner

Reputation: 5040

Here is an answer that needs only two operations:

printf("%d\n", (4 >> x) & 3);

Upvotes: 6

Paul R
Paul R

Reputation: 212979

After several false starts, a solution with six bitwise operations:

#include <stdio.h>

int main()
{
    int x, y;
    for (x = 0; x < 8; ++x)
    {
        y = !(x ^ 1) << 1 | !(x ^ 2);
        printf("x = %d, y = %d\n", x, y);
    }
    return 0;
}

(Note that it's arguable as to whether ! is a true bitwise operator.)

Upvotes: 1

user529758
user529758

Reputation:

This is insane, but I finally figured it out:

printf("%d\n", (3 & ~(x & 3)) & (0xfc >> (x << 1)));

Upvotes: 12

user1097048
user1097048

Reputation:

Not sure why but...

for (x = 0; x < 8; x++) {
    printf("%d %d\n",  x, !x|~3&x?0:3^x);
}

Upvotes: 1

unwind
unwind

Reputation: 399863

Not sure about the "bitwise" requirement ... If you want to compress the code, for some weird reason (the if version is very easy to understand which is a good thing), you might do something like this:

printf("%c\n", "210"[i == 0 ? 0 : i == 1 ? 1 : 2]);

This is of course almost the worst possible solution, since it's overly "clever": any reader of the code must spend valuable time to decode it, to understand what's going on.

Upvotes: 7

Related Questions