views:

223

answers:

2

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

A: 

Twidle in C/C++ is ~

J.J.
If you look carefully, this his example isn't strictly a one's compliment.
Evan Teran
he did not specify base 10 for those 2 digits and his subject was bit twiddling. Hence I assume it is base to. Also I assume if I give him the basic tool he can figure out how to apply it in a more complex way.
J.J.
He said "binary number" which is pretty clearly base 2.
Evan Teran
Yes even, but you are assuming that there are 32 bits in his first set of examples. I only see 2 in most and only 1 in another. I kindly disagree I think it is a one's compliment problem.
J.J.
Except that the poster edited his question and added "...and to clarify that this isn't a simple inversion".
Evan Teran
Yes "someone" clarified it. Your right. I am wrong.
J.J.
+10  A: 

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

unsigned myBitOperation(unsigned x)
{
    return ((x<<1) | (x>>1)) & (~x);
}
Uhall
nicely done, that is the right answer :)
Evan Teran
thanks//perfect! for some reason I forgot about shifting when I was thinking about a solution. *embarassed* that'll never happen again!!
nlucaroni