gpt4 book ai didi

c - 位集隶属函数

转载 作者:行者123 更新时间:2023-11-30 20:20:29 26 4
gpt4 key购买 nike

我正在编写一个位集成员谓词,它应该处理 x 的所有值:

int Contains(unsigned int A, int x)
{
return (x >= 0) && (x < 8 * sizeof A) && (((1u << x) & A) != 0);
}

有没有更高效的实现方式?

最佳答案

如果 x 无符号,您可以跳过下限检查。

来自 N1570:

6.3.1.3 Signed and unsigned integers

  1. When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
  2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type. 60)
unsigned int y = x;  // Wrap around if x is negative
return (y < CHAR_BIT * sizeof A) && (1u << y & A) != 0;

但不确定这是否真的带来任何有意义的改进。检查编译器输出以确保。

关于c - 位集隶属函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46196752/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com