c - 右移 float 的二进制表示 -0.0

标签 c floating-point double bit-manipulation

我正在编写一个程序来检查 double / float 的符号,首先我将数字的指针转换为一个 long int,然后我检查符号位是 0 还是 1。我不理解为什么使用此操作打印符号位 *pointer >> 63 是 -1 而不是 1?(假设 *pointer 是我将 double/float 转换成的 int64_t)

这是完整的代码:

    double d = -0.0;
    int64_t *pointer = (int64_t *) &d;
    if (*pointer >> 63)
       printf("negative number\n");
    else
       printf("positive number\n");
    // if i print the result of (*pointer >> 63), it gives me -1
    // so how can this go inside my if condition?

顺便说一下,64 位二进制打印 -0.0 给了我 100000000...000

最佳答案

由于浮点类型中存在带符号的零,并且可能存在 1 的补码整数类型,因此很难做到完全通用。

除了 (int64_t*)&d 的未定义性之外(您可以使用 union 双关语来解决),该方法将返回错误的 -0.0 符号。 .

幸运的是你可以使用 signbit()来自 math.h可能以不可移植的方式实现该功能。

关于c - 右移 float 的二进制表示 -0.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56169169/

相关文章:

c# - NaN 对 double 意味着什么?

c# - Double.MinValue、MaxValue 错误的编译时间常量 -- mscorlib

c - 超声波传感器与 PIC18F4520 Controller 连接

c - 以多线程方式进行矩阵乘法

c - 将 NAN float 转换为 int 时出现问题

Python Excel float 大不同

java - 返回数据不带两位小数 :Rounding Doubles

java - 双型比较器

c - 如何检查 nanosleep 循环中的错误

c - 为什么数组中的点头被认为是 'nod' 而不是 'struct nod' ?