
-----------------------------------
octopi
Thu Dec 14, 2006 2:18 pm

Flipping a number
-----------------------------------
I need to know how to do the following:


I'm in a loop, and I'm shifting the bits left, and depending on a condition adding a 1 to it. However, I need to then after this is done, flip the number (in its binary representation)


ie.   1001 0111 would become 11101001
(I need to mirror image it)


The way i'm getting the data I can't really reverse the loop so thats not an option.

Thanks.

-----------------------------------
bugzpodder
Thu Dec 14, 2006 4:21 pm


-----------------------------------
// swap odd and even bits
v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) > 2) & 0x33333333) | ((v & 0x33333333) > 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) > 8) & 0x00FF00FF) | ((v & 0x00FF00FF) > 16             ) | ( v                 0110 1001
i.e. one's compliment??

In which case you want to use the bitwise 'NOT' operator.


unsigned char c=127; //binary: 0111 1111
unsigned char flipped= ~c; //0x80, 128 or binary 1000 0000 


The bitwise NOT operation will give you the inverse number. 
(turns 1 to 0 and 0 to 1)


Here are some links:
http://en.wikipedia.org/wiki/Bitwise_operation
http://www.cplusplus.com/doc/tutorial/operators.html
http://www.informit.com/guides/content.asp?g=cplusplus&seqNum=163&rl=1

-----------------------------------
r.3volved
Wed Jan 03, 2007 5:43 pm


-----------------------------------
ok sorry, misread that

How are you storing that value??
If it's a string you can just use a for loop to reverse the output, or append to another string using a reverse iterator.

Or just use:
reverse( .begin(), .end() );

...I believe it requires an include for  
...and  of course

-----------------------------------
bugzpodder
Wed Jan 03, 2007 7:20 pm


-----------------------------------
you can reverse almost anything... including arrays
reverse(arr,arr+N)
