首页 > 解决方案 > 复制整数位的最快方法

问题描述

复制整数位的最快方法是什么。

例如,

17->10001

复制后: 1100000011

标签: c++coptimizationbit-manipulationbit

解决方案


看起来像是比特交错的变体。

交错位是显而易见的方式

(修改自http://graphics.stanford.edu/~seander/bithacks.html

unsigned int x = 17;
unsigned int z = 0; // z gets the resulting Morton Number.

for (int i = 0; i < sizeof(x) * CHAR_BIT; i++) // unroll for more speed...
{
  z |= (x & 1U << i) << i | (x & 1U << i) << (i + 1);
}

有关更多方法,请参阅http://graphics.stanford.edu/~seander/bithacks.html#InterleaveTableObvious


推荐阅读