我正在尝试执行一些高级位操作。假设我有数据位流,我想每X位插入一些其他位。
例如,对于位流:111111111和位:00000
如果X = 3,我会得到:110110110110
使用面具(在上面的示例中 - 面具110000)和轮班可能会起作用,但也将是一场噩梦。
感谢 伊泰
答案 0 :(得分:0)
分而治之:
我会根据X做出不同的方法。
当X = 2时:
//Precalculate insertion bits
//Insertion bits must be not more than 32 bits in this implementation.
uint bits;//input
ulong ins=(ulong)bits;
ins=(ins<<16|ins)&0xffff0000ffff;
ins=(ins<<8|ins)&0xff00ff00ff00ff;
ins=(ins<<4|ins)&0xf0f0f0f0f0f0f0f;
ins=(ins<<2|ins)&0x3333333333333333;
ins=(ins<<1|ins)&0x5555555555555555;
ins<<=1;
//Packet streaming bits per 32 bits
ulong str;//input
str=(str<<16|str)&0xffff0000ffff;
str=(str<<8|str)&0xff00ff00ff00ff;
str=(str<<4|str)&0xf0f0f0f0f0f0f0f;
str=(str<<2|str)&0x3333333333333333;
str=(str<<1|str)&0x5555555555555555;
//Returns full 64 bits
return str|ins;
当X = 3时:
//Precalculate insertion bits
//Insertion bits must be not more than 21 bits in this implementation.
uint bits;//input
ulong ins=(ulong)bits;
ins=(ins<<32|ins)&0xffff00000000ffff;
ins=(ins<<16|ins)&0x00ff0000ff0000ff;
ins=(ins<< 8|ins)&0xf00f00f00f00f00f;
ins=(ins<< 4|ins)&0x30c30c30c30c30c3;
ins=(ins<< 2|ins)&0x1249249249249249;
ins<<=2;
//Packet streaming bits per 42 bits
ulong str;//input
str=(str&0xffffffff00000000)<<16|str&0x00000000ffffffff;
str=(str&0x00000000ffff0000)<< 8|str&0xffff00000000ffff;
str=(str&0xff0000ff0000ff00)<< 4|str&0x00ff0000ff0000ff;
str=(str&0x00f00f00f00f00f0)<< 2|str&0xf00f00f00f00f00f;
str=(str&0x030c30c30c30c30c)<< 1|str&0x30c30c30c30c30c3;
//Returns 63 bits
return str|ins;
依旧...... (我还没有测试过这个,但我希望你能理解它。)