简体   繁体   English

我正在寻找一种算法来混淆(32位)int的前25位

[英]I am looking for an algorithm to shuffle the first 25 bits of a (32-bit) int

All of the bit shuffling algorithms I've found deal with 16-bit or 32-bit, which means that even if I use only the first 25-bits of an int, the shuffle will leave bits outside. 我发现的所有位混洗算法都处理16位或32位,这意味着即使我只使用int的前25位,shuffle也会将位留在外面。 This function is in an inner loop of a CPU-intensive process so I'd prefer it to be as fast as possible. 此函数位于CPU密集型进程的内部循环中,因此我希望它尽可能快。 I've tried modifying the code of the Hacker's Delight 32-bit shuffle algorithm 我已经尝试修改Hacker的Delight 32位shuffle算法的代码

x = (x & 0x0000FF00) << 8 | (x >> 8) & 0x0000FF00 | x & 0xFF0000FF;
x = (x & 0x00F000F0) << 4 | (x >> 4) & 0x00F000F0 | x & 0xF00FF00F;
x = (x & 0x0C0C0C0C) << 2 | (x >> 2) & 0x0C0C0C0C | x & 0xC3C3C3C3;
x = (x & 0x22222222) << 1 | (x >> 1) & 0x22222222 | x & 0x99999999;

but am having difficulty in doing some partly because I'm not sure where the masks come from. 但我很难做一些,因为我不确定面具来自哪里。 I tried shifting the number and re-shuffling but so far the results are all for naught. 我尝试改变数字并重新洗牌,但到目前为止结果都是徒劳的。 Any help would be GREATLY appreciated! 任何帮助将不胜感激!

(I am using C but I can convert an algorithm from another language) (我使用C但我可以转换另一种语言的算法)

First, for the sake of evenness, we can extend the problem to a 26-bit shuffle by remembering that bit 25 will appear at the end of the interleaved list, so we can trim it off after the interleaving operation without affecting the positions of the other bits. 首先,为了均匀,我们可以通过记住位25将出现在交错列表的末尾来将问题扩展到26位洗牌,因此我们可以在交错操作之后将其修剪掉,而不会影响位置。其他比特。

Now we want to interleave the first and second sets of 13 bits; 现在我们要交织第一组和第二组13位; but we only have an algorithm to interleave the first and second sets of 16 bits. 但我们只有一个算法来交错第一和第二组16位。

A straightfoward approach might be to just move the high and low parts of x into more workable positions before applying the standard algorithm: 一种直接的方法可能是在应用标准算法之前将x高低部分移动到更可行的位置:

x = (x & 0x1ffe000) << 3 | x & 0x00001fff;

x = (x & 0x0000FF00) << 8 | (x >> 8) & 0x0000FF00 | x & 0xFF0000FF;
x = (x & 0x00F000F0) << 4 | (x >> 4) & 0x00F000F0 | x & 0xF00FF00F;
x = (x & 0x0C0C0C0C) << 2 | (x >> 2) & 0x0C0C0C0C | x & 0xC3C3C3C3;
x = (x & 0x22222222) << 1 | (x >> 1) & 0x22222222 | x & 0x99999999;

The zeroes at the top of each half will be interleaved and appear at the top of the result. 每半个顶部的零将交错显示在结果的顶部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM