Posted: 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.
Sponsor Sponsor
bugzpodder
Posted: Thu Dec 14, 2006 4:21 pm Post subject: (No 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);
ownageprince
Posted: Tue Jan 02, 2007 7:52 pm Post subject: (No 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?
[Gandalf]
Posted: Tue Jan 02, 2007 8:50 pm Post subject: (No 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.
r.3volved
Posted: Wed Jan 03, 2007 5:28 pm Post subject: (No 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.
Posted: Wed Jan 03, 2007 5:43 pm Post subject: (No 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
bugzpodder
Posted: Wed Jan 03, 2007 7:20 pm Post subject: (No subject)
you can reverse almost anything... including arrays
reverse(arr,arr+N)