对于以下代码
static inline float fix2float(int64_t f)
{
return (float)f / (1 << 60); // <-- error here
}
Run Code Online (Sandbox Code Playgroud)
编译器给了我这些警告.
warning: left shift count >= width of type
warning: division by zero
Run Code Online (Sandbox Code Playgroud)
当64> 60时,为什么编译器会发出这些警告?
1在C实现中不是64位数字.它是一个int,可能是32位.
编译器不会查看表达式并看到有int64_t涉及的内容,因此其他算法应该使用64位.它从它们的部分构建表达式.在该部分中(1 << 60),编译器识别一个并给它一种类型int,因为这就是C规则对简单常量值所说的(对于十六进制表示法,后缀和大值有附加规则).因此,1 << 60尝试将int60 位移位.由于int您的系统上只有32位,编译器会发出警告.
写这个的更好方法是return f * 0x1p-60f;.0x1p-60f是一个float常数,值为2 -60.