__builtin_clz() is negative

__builtin_clz() is negative

本文关键字:is negative builtin clz      更新时间:2023-10-16

我有一些这样的代码:

int foo(unsigned long long x) {
    unsigned int x1 = (unsigned int)(x >> 32);
    unsigned int x2 = (unsigned int)(x);
    if (x == 0) {
        cout << x1 << " " << __builtin_clz(x1) << endl;
        cout << x2 << " " << __biultin_clz(x2) << endl;
    }
}

x = 0上的输出为:

0 587581823
0 -32

最奇怪的是,这里等于587581823总是不同的随机数(有时小于 0(__builtin_clz(x1)并且__builtin_clz(x2)总是-32

如果您查看 gcc 文档以了解__builtin_ctz我们有:

内置功能:int __builtin_ctz (unsigned int x)

返回 x 中尾随 0 位的数,从最低有效位位置开始。如果 x 为 0,则结果未定义。[强调我的]

未定义

就是未定义。您看到的结果完全任意的数字完全在"未定义"的范围内。

不能使用值为 0 的__builtin_clz

文档 说:

— 内置函数:int __builtin_clz(无符号 int x(返回 x 中的前导 0 位数,从最高有效位开始 位置。如果 x 为 0,则结果未定义