2012-09-06 25 views
2

我正在嘗試執行一些高級位操作。比方說,我有比特流的數據,我想插入其他比特每X比特。高級位操作 - 位流中的多路複用位

例如,對於比特流:111111111和位:00000
,其中X = 3,我會得到:110110110110

使用掩膜(在上文的110000掩模的例子),並轉移將可能工作,但也將是一場噩夢。

感謝 伊泰

+0

你真的必須在那麼低的水平上多路複用嗎?什麼是字節,單詞或某種數據包格式?什麼是應用程序? –

+0

嗨,約翰。該應用程序是數字通信系統中的導頻插入 – user1651647

+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; 

等等...... (我還沒有測試過這個,但我希望你能明白這個意思。)

+0

這可能會遲到...但對於其他人有同樣的問題:) – eivour