I have an array of char (usually thousands of bytes long) read from a file, all composed of 0 and 1 (not '0' and '1', in which case I could use strtoul
). I want to pack these into single bits, thus converting each 32 char into a single uint32_t. Should I write a bit shift operation with 32 parts, or is there a saner way?
out[i/32] =
data[i] << 31 |
data[i+1] << 30 |
data[i+2] << 29 |
data[i+3] << 28 |
data[i+4] << 27 |
data[i+5] << 26 |
data[i+6] << 25 |
data[i+7] << 24 |
data[i+8] << 23 |
data[i+9] << 22 |
data[i+10] << 21 |
data[i+11] << 20 |
data[i+12] << 19 |
data[i+13] << 18 |
data[i+14] << 17 |
data[i+15] << 16 |
data[i+16] << 15 |
data[i+17] << 14 |
data[i+18] << 13 |
data[i+19] << 12 |
data[i+20] << 11 |
data[i+21] << 10 |
data[i+22] << 9 |
data[i+23] << 8 |
data[i+24] << 7 |
data[i+25] << 6 |
data[i+26] << 5 |
data[i+27] << 4 |
data[i+28] << 3 |
data[i+29] << 2 |
data[i+30] << 1 |
data[i+31];
If this monstrous bit shift is the fastest in run time, then I'll have to stick to it.