繁体   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