是否可以reinterpret_cast一个整数float? [英] Is it safe to reinterpret_cast an integer to float?

查看:897
本文介绍了是否可以reinterpret_cast一个整数float?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我最初错误地询问了 static_cast 这是为什么顶部的回答最初提到 static_cast

Note: I mistakenly asked about static_cast originally; this is why the top answer mentions static_cast at first.

我有一些二进制文件具有小端浮点值。我想以机器无关的方式读它们。

I have some binary files with little endian float values. I want to read them in a machine-independent manner. My byte-swapping routines (from SDL) operate on unsigned integers types.

在int和float之间转换是否安全?

Is it safe to simply cast between ints and floats?

float read_float() {
    // Read in 4 bytes.
    Uint32 val;
    fread( &val, 4, 1, fp );
    // Swap the bytes to little-endian if necessary.
    val = SDL_SwapLE32(val);
    // Return as a float
    return reinterpret_cast<float &>( val );  //XXX Is this safe?
}



我希望这个软件尽可能便携。

I want this software to be as portable as possible.

推荐答案

好吧, static_cast ,但这可能不是你需要的。将整数值转换为float类型将仅尝试在目标浮点类型中表示相同的整数值。也就是说类型 int 5 将变成 5.0 code> float (假设它可以精确地表示)。

Well, static_cast is "safe" and it has defined behavior, but this is probably not what you need. Converting an integral value to float type will simply attempt to represent the same integral value in the target floating-point type. I.e. 5 of type int will turn into 5.0 of type float (assuming it is representable precisely).

你似乎正在做的是构建 Uint32 变量的内存块中的c $ c> float 值。要生成结果 float 的值,您需要重新解释 该内存。这可以通过 reinterpret_cast

What you seem to be doing is building the object representation of float value in a piece of memory declared as Uint32 variable. To produce the resultant float value you need to reinterpret that memory. This would be achieved by reinterpret_cast

assert(sizeof(float) == sizeof val);
return reinterpret_cast<float &>( val );

或者,如果你喜欢,同样的东西的指针版本

or, if you prefer, a pointer version of the same thing

assert(sizeof(float) == sizeof val);
return *reinterpret_cast<float *>( &val );

虽然这种类型的打字不能保证在遵循严格别名语义。另一种方法是这样做

Although this sort of type-punning is not guaranteed to work in a compiler that follows strict-aliasing semantics. Another approach would be to do this

float f;

assert(sizeof f == sizeof val);
memcpy(&f, &val, sizeof f);

return f;

或者你可以使用众所周知的联合黑客来实现内存重新解释。具有严格别名语义的某些编译器保留基于联合的方法作为正式支持的类型冲突方法

Or you can use the well-known union hack to implement memory reinterpretation. Certain compilers with strict-aliasing semantics reserve the union-based approach as an officially supported method of type-punning

assert(sizeof(float) == sizeof(Uint32));

union {
  Uint32 val; 
  float f;
} u = { val };

return u.f;

这篇关于是否可以reinterpret_cast一个整数float?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆