nlucaroni
nlucaroni

Reputation: 47934

Bit Twiddle to perform this conversion

curious if anyone might have some insight in how I would do the following to a binary number:

convert

   01+0 -> 10+1 (+ as in regular expressions, one or more)
    01 -> 10  
    10 -> 01  

so,

10101000010100011100
01010100101010100010

and to clarify that this isn't a simple inversion:

000000100000000000
000001010000000000

I was thinking regex, but I'm working with binary numbers and want to stay that way. The bit twiddling hacks page hasn't given me any insight either. This clearly has some essence of cellular automata. So, anyone have a few bit operations that can take care of this? (no code is necessary, I know how to do that).

Upvotes: 2

Views: 420

Answers (2)

Uhall
Uhall

Reputation: 5781

Let's say x is your variable. Then you'd have:

unsigned myBitOperation(unsigned x)
{
    return ((x<<1) | (x>>1)) & (~x);
}

Upvotes: 11

J.J.
J.J.

Reputation: 4872

Twidle in C/C++ is ~

Upvotes: -2

Related Questions