确定位是否设置为整数数据类型的最快方法 [英] fastest way to determine if a bit is set in a integer data type

查看:79
本文介绍了确定位是否设置为整数数据类型的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种根据某些特定算法计算哈希值的方法.

I have a method that computes a hash value as per some specific algorithm.

uint8_t cal_hash(uint64_t _in_data) {
    uint8_t hash;
    // algorithm
    // bit at hash[0] = XOR of some specific bits in _in_data
    // repeat above statement for other indexed bits of hash 
    return hash;
}

我想知道什么是访问和设置整数数据类型中相应位的最有效方法. 我已经尝试过

I want to know what could be the most efficient way to access and set corresponding bits in an integer datatype. I have already tried things like

(((x) & (1<<(n)))?1:0)

确定任何索引处的位是1还是0.还有什么比这更好的吗?

to determine if a bit is 1 or 0 at any index. Anything better than this ?

推荐答案

您首先要考虑的是拥有正确且可移植的版本.如今,编译器将非常巧妙地优化此类位操作.

Your first concern should be to have a correct and portable version. Compilers nowadays will then optimize such bit operations quite cleverly.

您应始终注意所使用的掩码与要测试的数据类型相对应.使用intunsigned可能还不够,因为您对uint64_t的位感兴趣,并且移位超过位是不确定的行为.

You should always take care that the mask you are using corresponds to the data type that you are testing. Using an int or unsigned might not be enough since you are interested in the bits of a uint64_t and shifting for more than there are bits is undefined behavior.

在您的情况下,您可能会使用类似的

In your case you would probably use something like

(UINT64_C(1) << (n))

遮罩.如果您想以更通用的方式执行此操作,则必须通过类似

for the mask. If you want to do this in a more generic way you'd have to obtain a 1 of your base type by something like

(1 ? 1U : (X))

一起在宏中

#define MASK(X, N) ((1 ? 1U : (X)) << (N))

然后测试看起来像

#define BIT(X, N) !!((X) & MASK(X, N))

这篇关于确定位是否设置为整数数据类型的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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