通过附加两个 int 的二进制表示来创建 double

Create double by appending binary representations of two ints

我正在尝试通过附加两个 int 的二进制表示来创建 double。这就是我现在拥有的:

int i = arc4random();
*(&i+1) = arc4random();
double d = *(double*)&i;

我希望double指针也使用&i+1地址中的值,事实确实如此。当我打印 i*(&i+1) 的二进制表示并将它们与 d 的二进制表示进行比较时,d 是由附加 *(&i+1)i 组成的。所以 *(&i+1) 排在第一位?!为什么会这样?

编辑: 另请查看 Juan Catalan 和 Mark Segal 的答案,了解我使用联合所做的正确方法是什么。

改用 union。您仍然可以生成 NaN 但不会有内存管理问题。

这就是 union 的全部目的,在几种不同的类型之间共享一个内存块。

确保在您的架构中 sizeof(double) 等于两倍 sizeof(int)

您可以使用联合,如下所示:

typedef union {
    double d;
    struct {
        int a;
        int b;
    } integers;
} double_generator;

int main(void) {
    double_generator g;
    g.integers.a = arc4random();
    g.integers.b = arc4random();

    // g.d is now a "randomly generated double"

    return 0;
}

或"manually",可能不安全,自己做:

int main(void) {
    double d;
    *((int *)&d) = arc4random();
    *(((int *)&d) + 1) = arc4random();
    printf("%f", d);
    return 0;
}

在这两种情况下,您只需寻址相同的内存,就像它是 intdouble 一样。这可以生成每个可能的 double 值,包括 NaNInfinity.

但是,此代码假定 sizeof(double) 是(至少)两倍 sizeof(int)。如果不是,则必须引入不同的代码来处理它。

When I print the binary representations of i and *(&i+1) and compare them to the binary representation of d, d is composed by appending *(&i+1) and i. So *(&i+1) comes first?! Why is this the case?

字节的实际顺序取决于底层硬件架构的'Endian-ness'。

小端架构:

1) the lowest address byte contains the least significant 8 bits of the total variable  
2) the highest address byte contains the most significant 8 bits of the total variable.