I need to do an arbitrary reorder of a 7 bit value (Yes I know I should be using a table) and am wondering if there are any bit hacks to do this.
Example:
// <b0, b1, b2, b3, b4, b5, b6> -> <b3, b2, b4, b1, b5, b0, b6> // the naive way out = (0x020 & In) << 5 | (0x008 & In) << 2 | (0x040 & In) | (0x012 & In) >> 1 | (0x004 & In) >> 2 | (0x001 & In) >> 3; // 6 ANDs, 5 ORs, 5 shifts = 16 ops
edit: I was thinking of something along the lines of this
Just for kicks and because I was AFTK I’m trying a brute force search for solutions of the form:
((In * C1) >> C2) & 0x7f
No solutions found.
Have a look at the compiler output of your ‘naive’ code, it might surprise you. I once did something like that and the compiler (VC++2005) completely changed the values of all the ands and shifts for me to make them more efficient, eg I’m sure it would remove your ‘(0x001 & In) >> 3’.
But yes, if the reshuffle is a fixed function then a table is probably best.
Update
For a laugh I looked at the compiler output from VC++ 2005….
First I tried a constant value for ‘In’ but the compiler wasn’t fooled one bit, it produced this code:
ie. it completely optimized it away.
So … I tried a proper input and got this:
That’s four shift operations, five ANDs, four ORs – not bad for six inputs. Probably better than most people could do by hand.
It’s probably also optimized for out-of-order execution so it’ll be less clock cycles than it seems. 🙂