c:更改变量类型而不进行强制转换

Sch*_*tod 3 c types casting

我正在将uint32_t更改为float但不更改实际位.

只是为了确定:我不想施展它.那么float f = (float) i是什么我wan't做的,因为它改变了位正好相反.

我将使用它将我的(伪)随机数转换为浮点数,而不进行不必要的数学运算.

我目前正在做什么,已经在做什么是这样的:

float random_float( uint64_t seed ) {

    // Generate random and change bit format to ieee
    uint32_t asInt = (random_int( seed ) & 0x7FFFFF) | (0x7E000000>>1);

    // Make it a float
    return *(float*)(void*)&asInt; // <-- pretty ugly and nees a variable
}                                                                      
Run Code Online (Sandbox Code Playgroud)

问题:现在我想摆脱asInt变量,我想知道是否有更好/不那么丑陋的方式然后获取此变量的地址,将其转换两次并再次取消引用它?

Ish*_*led 6

您可以尝试使用union - 只要确保类型的内存大小相同:

union convertor {
    int asInt;
    float asFloat;
};
Run Code Online (Sandbox Code Playgroud)

然后你可以将你的int分配给asFloat(或者如果你愿意,可以另外一种方式).当我需要一方面进行按位操作并且另一方面仍然在数字上获得uint32_t表示时,我会使用它

[编辑]
就像许多评论员合理陈述的那样,你必须考虑像NAN,+ INF,-INF,+ 0,-0这样的整数无法呈现的值.