(e-mail address removed) says...
I have a long x;
I want to write a function
long f(long x, int k)
such that it extracts every k-th bit of x, concatenates
them and returns it. Anyone can help me in writing this
function?
examples
x = 10101010 k = 1 f(x) = 10101010
x = 10101010 k = 2 f(x) = 1111
x = 10101010 k = 3 f(x) = 010
x = 10101010 k = 4 f(x) = 11
Any bit gurus here who can help me?
Its not portable, but I'm sure you can adapt it to your platform of choice:
long f(long x, int k) {
switch (k) {
case 1: return x;
case 2: x &= 0xAAAAAAAA;
x = (x | (x >> 1)) & 0x66666666;
x = (x | (x >> 2)) & 0x1E1E1E1E;
x = (x | (x >> 4)) & 0x01FE01FE;
x = (x | (x >> 8)) & 0x0001FFFE;
return x >> 1;
case 3: x &= 0x24924924;
x = (x | (x >> 2)) & 0x0C30C30C;
x = (x | (x >> 4)) & 0x0C03C03C;
x = (x | (x >> 8)) & 0x0C0003FC;
x = (x | (x >> 16)) & 0x00000FFC;
return x >> 2;
case 4: x &= 0x88888888;
x = (x | (x >> 3)) & 0x18181818;
x = (x | (x >> 6)) & 0x00780078;
x = (x | (x >> 12)) & 0x000007F8;
return x >> 3;
case 5: x &= 0x21084210;
x = (x | (x >> 4)) & 0x0300C030;
x = (x | (x >> 8)) & 0x030000F0;
x = (x | (x >> 16)) & 0x000003F0;
return x >> 4;
case 6: x &= 0x20820820;
x = (x | (x >> 5)) & 0x20060060;
x = (x | (x >> 10)) & 0x200001E0;
x = (x | (x >> 20)) & 0x000003E0;
return x >> 5;
case 7: x &= 0x08102040;
x = (x | (x >> 6)) & 0x003000C0;
x = (x | (x >> 12)) & 0x000003C0;
return x >> 6;
case 8: x &= 0x80808080;
x = (x | (x >> 7)) & 0x01800180;
x = (x | (x >> 14)) & 0x00000780;
return x >> 7;
case 9: x &= 0x04020100;
x = (x | (x >> 8)) & 0x04000300;
x = (x | (x >> 16)) & 0x00000700;
return x >> 8;
case 10: x &= 0x20080200;
x = (x | (x >> 9)) & 0x20000600;
x = (x | (x >> 18)) & 0x00000E00;
return x >> 9;
case 11: x &= 0x00200400;
x = (x | (x >> 10)) & 0x00000C00;
return x >> 10;
case 12: x &= 0x00800800;
x = (x | (x >> 11)) & 0x00001800;
return x >> 11;
case 13: x &= 0x02001000;
x = (x | (x >> 12)) & 0x00003000;
return x >> 12;
case 14: x &= 0x08002000;
x = (x | (x >> 13)) & 0x00006000;
return x >> 13;
case 15: x &= 0x20004000;
x = (x | (x >> 14)) & 0x0000C000;
return x >> 14;
case 16: x &= 0x80008000;
x = (x | (x >> 15)) & 0x00018000;
return x >> 15;
case 17: case 18: case 19: case 20: case 21:
case 22: case 23: case 24: case 25: case 26:
case 27: case 28: case 29: case 30: case 31:
case 32: return (x >> (k-1)) & 1;
default: break;
}
return 0;
}