2010-04-02 50 views
2

有沒有什麼聰明的方法來混合兩個比特序列,使得第一個序列的比特位於奇數位置,而第二個序列的比特位於偶數位置。
兩個序列都不超過16b,所以輸出將適合32位整數。兩個比特序列的混合

實施例:

First sequence : 1 0 0 1 0 0 
Second sequence : 1 1 1 0 1 1 
Output   : 1 1 0 1 0 1 1 0 0 1 0 1 

我考慮製作大小爲2^16的整數數組,然後輸出將是:

arr[first] << 1 | arr[second] 
+5

http://graphics.stanford.edu/~seander/bithacks.html#InterleaveBMN – kennytm 2010-04-02 12:33:15

+0

KennyTM:將其作爲答案發布,以便我可以接受itp。 – 2010-04-02 21:04:34

回答

1

在C#:

public Int32 Mix(Int16 b1, Int16 b2) 
{ 
    Int32 res = 0; 
    for (int i=0; i<16; i++) 
    { 
    res |= ((b2 >> i) & 1) << 2*i; 
    res |= ((b1 >> i) & 1) << 2*i + 1; 
    } 
    return res; 
} 
+0

我知道如何使用for循環... – 2010-04-02 12:34:54

+2

抱歉,它沒有在您的問題中提到... :) – PierrOz 2010-04-02 13:00:46