5

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
8
  • printf("%d\n", x & 0xfc || !x ? 0 : 3 - x & 3); should do the job. Commented Jan 14, 2014 at 9:49
  • 3
    @H2CO3 I don't think the ternary operator classifies as bitwise... Commented Jan 14, 2014 at 9:50
  • @RichardJ.RossIII I didn't say it was bitwise. It avoids the if-else, at least. Commented Jan 14, 2014 at 9:51
  • @KerrekSB, yes, even for x = 0 Commented Jan 14, 2014 at 9:52
  • 1
    @H2CO3: Ninja what? :-) Commented Jan 14, 2014 at 9:52

5 Answers 5

12

This is insane, but I finally figured it out:

printf("%d\n", (3 & ~(x & 3)) & (0xfc >> (x << 1)));
Sign up to request clarification or add additional context in comments.

8 Comments

@PaulR No problem. At first I thought you spotted some UB, but I just couldn't find any.
Congratulations on having spent your life on something meaningful. :-)
One final nitpick: - is not a bitwise operator. Bonus points if you can replace it with a bitwise equivalent.
@KerrekSB - At least he wasn't smoted by a dragon!
@PaulR Yup. Thinking about substituting it with a bitwise one.
|
7

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.

1 Comment

Thanks unwind, thats nice, is not a requirement (just for fun)
6

Here is an answer that needs only two operations:

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

3 Comments

Probably this was what OP is really looking for. +1.
+1: very good, although strictly speaking it's UB for x < 0 or x >= sizeof(int) * CHAR_BIT.
True; I assumed the question was only about the input range 0 to 7.
1

Not sure why but...

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

1 Comment

Nice, but I want to avoid ternary operator
1

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.)

1 Comment

Nice. I've got a simpler formula without any logical operations at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.