【发布时间】:2014-11-03 05:48:32
【问题描述】:
我需要对一个 16 位无符号整数进行洗牌,使偶数索引位于低字节,奇数索引位于高字节。
input:
fedcba98 76543210 (contiguously numbered)
output:
fdb97531 eca86420 (even and odd separated)
我的代码现在是这样的:
typedef unsigned short u16;
u16 segregate(u16 x)
{
u16 g = (x & 0x0001);
u16 h = (x & 0x0004) >> 1;
u16 i = (x & 0x0010) >> 2;
u16 j = (x & 0x0040) >> 3;
u16 k = (x & 0x0100) >> 4;
u16 l = (x & 0x0400) >> 5;
u16 m = (x & 0x1000) >> 6;
u16 n = (x & 0x4000) >> 7;
u16 o = (x & 0x0002) << 7;
u16 p = (x & 0x0008) << 6;
u16 q = (x & 0x0020) << 5;
u16 r = (x & 0x0080) << 4;
u16 s = (x & 0x0200) << 3;
u16 t = (x & 0x0800) << 2;
u16 u = (x & 0x2000) << 1;
u16 v = (x & 0x8000);
return g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v;
}
我想知道是否有比简单地提取和移动每个单独的位更优雅的解决方案?
【问题讨论】:
-
"看起来很慢" 放一个profiler就可以了。这会告诉你它是否真的很慢。
-
它看起来很慢,但它实际上对于您的特定应用程序来说太慢了吗?测量两次,切割一次。
-
Related,我想。
-
只需将“0 2 4 6 8 10 12 14 1 3 5 7 9 11 13 15”输入此页面:" Code generator for bit permutations"。
-
似乎按预期工作:ideone.com/05oXgr
标签: c++ c bit-manipulation z-order-curve