Computer Science Canada

Flipping a number

Author:  octopi [ Thu Dec 14, 2006 2:18 pm ]
Post subject:  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.

Author:  bugzpodder [ Thu Dec 14, 2006 4:21 pm ]
Post subject: 

// swap odd and even bits
v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1);
// swap consecutive pairs
v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2);
// swap nibbles ...
v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4);
// swap bytes
v = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8);
// swap 2-byte long pairs
v = ( v >> 16 ) | ( v << 16);

Author:  ownageprince [ Tue Jan 02, 2007 7:52 pm ]
Post subject: 

Well can't you just store the 1001 0111 or any other number into a string then cout it in a for loop in reverse format?

Author:  [Gandalf] [ Tue Jan 02, 2007 8:50 pm ]
Post subject: 

ownageprince wrote:
Well can't you just store the 1001 0111 or any other number into a string then cout it in a for loop in reverse format?

That's a lot more inefficient than it sounds... Especially if you don't need the number as a string in the first place.

Author:  r.3volved [ Wed Jan 03, 2007 5:28 pm ]
Post subject: 

Are you trying to get the inverse of the binary digits??
i.e. 1001 0110 ==> 0110 1001
i.e. one's compliment??

In which case you want to use the bitwise 'NOT' operator.

code:

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

Author:  r.3volved [ Wed Jan 03, 2007 5:43 pm ]
Post subject: 

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 <algorithm>
...and <string> of course

Author:  bugzpodder [ Wed Jan 03, 2007 7:20 pm ]
Post subject: 

you can reverse almost anything... including arrays
reverse(arr,arr+N)


: