In C++ I want to encode the bits of 3 unsigned variables into one. More precisely, when the three variables are:
A: a3 a2 a1 a0
B: b3 b2 b1 b0
C: c3 c2 c1 c0
then the output variable shall contain such triples:
D: a3 b3 c3 a2 b2 c2 a1 b1 c1 a0 b0 c0
Let's assume that the output variable is large enough for all used bits. I have come up with
unsigned long long result(0);
unsigned a,b,c; // Some numbers to be encoded
for(int level=0;level<numLevels;++level)
{
int q(1<<level); // SearchBit q: 1<<level
int baseShift((3*level)-level); // 0,2,4,6
result|=( ((a&q)<<(baseShift+2)) | ((b&q)<<(baseShift+1)) | ((c&q)<<(baseShift)) );
}
...and it works sufficiently. But I wonder if there is a solution that does not require a loop that iterates over all bits separately.
sizeof(unsigned long)before you get too carried away - it's very likely less than 12. Why are you wanting to do this?unsigned longon any modern mainstream platform.