Reputation: 3
I'm having trouble thinking about how to swap the middle 4 values of a given 8 bit number while preserving the 2 bits on each side of the middle. Here's a diagram:
Given an 8-bit number |76543210|, swap 2 with 4 and 3 with 5. However, you must also preserve the digits 7,6, 1, and 0.
Here's pseudo-code for what I'm currently doing (this may be way more complex than what I actually need to do; I'm new to bitwise operations)
mask1 = 00001100
mask2 = 00110000
temp1 = (original number) AND mask1 // Extract only the bits we care about swapping.
temp2 = (original number) AND mask2
temp1 << 2 // Perform the swap of the inner four bits.
temp2 >> 2
swapped = temp1 OR temp2 // The final swapped number, but the outer digits
// haven't been preserved.
Is there a mask I would use or something to make sure that the outer digits get reinstated after the shifts occur?
Right now I'm thinking that I might zero out the middle 4 digits and then do (original number) OR swapped, but that's seems like it's hacky.
Thanks for any help with this!
Upvotes: 0
Views: 924
Reputation: 4369
When you assign values of temp1 and temp2, there are only bits you want (as you have used AND operator).
But there is one step you are missing in your solution, you need to merge it all together with original value.
What you need to do is too copy an original value (if you don't want to lose it), remove values you are modifying (swaps), and place there your temp1 and temp2 with OR operator.
How to remove bits from original value? use the trick below:
temp3 = (origianl number) AND ~(mask1 OR mask2)
~ is the negation.
Upvotes: 1