压缩一个十六进制数 [英] Compact a hex number

查看:267
本文介绍了压缩一个十六进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种聪明的(即:无分支的)方式来压缩"十六进制数.基本上将所有0都移到一侧?

Is there a clever (ie: branchless) way to "compact" a hex number. Basically move all the 0s all to one side?

例如:

0x10302040 -> 0x13240000

0x10302040 -> 0x00001324

我查看了 Bit Twiddling Hacks ,但什么也没看到.

I looked on Bit Twiddling Hacks but didn't see anything.

它用于SSE数值透视算法.我需要删除所有变为0的枢轴.我可以使用_mm_cmpgt_ps查找良好的枢轴,使用_mm_movemask_ps将其转换为蒙版,然后使用一点技巧获得类似上面的内容.十六进制值合并到掩码中,以使用_mm_shuffle_ps指令在SSE 128位寄存器上执行置换.

It's for a SSE numerical pivoting algorithm. I need to remove any pivots that become 0. I can use _mm_cmpgt_ps to find good pivots, _mm_movemask_ps to convert that in to a mask, and then bit hacks to get something like the above. The hex value gets munged in to a mask for a _mm_shuffle_ps instruction to perform a permutation on the SSE 128 bit register.

推荐答案

_pext计算掩码:

mask = arg;
mask |= (mask << 1) & 0xAAAAAAAA | (mask >> 1) & 0x55555555;
mask |= (mask << 2) & 0xCCCCCCCC | (mask >> 2) & 0x33333333;

首先对位或对位进行运算,然后对四元组进行运算.掩码可防止移位后的值溢出到其他数字.

First do bit-or on pairs of bits, then on quads. Masks prevent shifted values from overflowing to other digits.

以这种方式或harold的方式(可能更快)来计算蒙版之后,您并不需要_pext的全部功能,因此,如果目标硬件不支持它,则可以用以下方式替换它:

After computing mask this way or harold's way (which is probably faster) you don't need the full power of _pext, so if targeted hardware doesn't support it you can replace it with this:

for(int i = 0; i < 7; i++) {
    stay_mask = mask & (~mask - 1);
    arg = arg & stay_mask | (arg >> 4) & ~stay_mask;
    mask = stay_mask | (mask >> 4);
}

如果有空间,每次迭代会将所有半字节向右移动一位. stay_mask标记处于其最终位置的位.与Hacker的Delight解决方案相比,此方法使用的操作要少一些,但仍可以从分支中受益.

Each iteration moves all nibbles one digit to the right if there is some space. stay_mask marks bits that are in their final positions. This uses somewhat less operations than Hacker's Delight solution, but might still benefit from branching.

这篇关于压缩一个十六进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆