簡體   English   中英

從二進制數中提取ODD數字的最佳方法

[英]Best way to extract ODD digits from a binary number

給定64位數字,我需要從中提取每一位,並將其轉換為數字:

decimal:  357
binary:   0000 0001 0110 0101
odd bits:  0 0  0 1  1 0  1 1
decimal:  27

有沒有想過一個好的算法方法呢? 不,不是HW,這是真實的世界使用:)

我會一次兩個執行算術右移(直到二進制數的長度)。 在我的邏輯中使用的這個>>用於算術移位。

(注意:在C語言中,右移可能是也可能不是算術!)

喜歡,

int count=0;
bit=extractLastbit(binary_representation_of_the_number);

while(count!=binaryLength){
  // binaryLength is the length of the binary_representation_of_the_number
  binary_representation_of_the_number=binary_representation_of_the_number>>2;

  bit.appendLeft(extractLastbit(binary_representation_of_the_number);
  count=count+2;
}

哪里,

extractLastBit()提取二進制數的LSB; appendLeft()執行將新提取的位移位到舊位的左側。

創建一個包含256個條目的表來查找每個字節。 表中的條目值將轉換為數字。 然后將4個字節與移位一起粘貼以得出最終數字。

這是一個縮小范圍的示例,以便您了解這個想法。 查找部分使用4位而不是8位:

0000 = 00
0001 = 01
0010 = 00
0011 = 01
0100 = 10
0101 = 11
...

查找說01010010。分解成0101和0010.看看那些我們得到11,和00並粘貼在一起:1100

使用256表,您將需要8次查找與相應的粘貼。 如果你有2 ** 16個條目的內存,那么你只需要進行四次查找,並且粘貼也會相應減少。

該表不具有2的均勻功率。 例如,有1024個條目(2 ** 10),有7個查找。 當表指數恰好是2的冪(2,4,8,16或32)時,只有經濟。

請參見如何解交織位(UnMortonizing?)

x = x& 0x5555555555555555; //restrict to odd bits.
x = (x | (x >> 1)) & 0x3333333333333333;
x = (x | (x >> 2)) & 0x0f0f0f0f0f0f0f0f;
x = (x | (x >> 4)) & 0x00ff00ff00ff00ff;
x = (x | (x >> 8)) & 0x0000ffff0000ffff;
x = (x | (x >>16)) & 0x00000000ffffffff;

這是我最終想出的 - 每個ODD位從/到X值,每個偶數位 - 從/到Y.我必須用JavaScript編寫它。

function xyToIndex(x, y) {
    // Convert x,y into a single integer with alternating bits
    var mult = 1, result = 0;
    while (x || y) {
        result += (mult * (x % 2));
        x = Math.floor(x / 2);
        mult *= 2;
        result += (mult * (y % 2));
        y = Math.floor(y / 2);
        mult *= 2;
    }
    return result;
}

function indexToXY(index) {
    // Convert a single integer into the x,y coordinates
    // Given a 64bit integer, extract every odd/even bit into two 32bit values
    var x = 0, y = 0, mult = 1;
    while (index) {
        x += mult * (index % 2);
        index = Math.floor(index / 2);
        y += mult * (index % 2);
        index = Math.floor(index / 2);
        mult *= 2;
    }
    return [x, y];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM