错误:二进制表达式的操作数无效('浮动'浮动')返回(x&(1<< 31))== 0

时间:2018-02-08 07:49:36

标签: c++

嗨,我有这样的代码:

STATIC bool is_pos_float(float x) {
  return (x & (1 << 31)) == 0;
}

但是在编译之后,它显示:

error: invalid operands to binary expression ('float' and 'float')
  return (x & (1 << 31)) == 0;

问题是什么?

2 个答案:

答案 0 :(得分:2)

内置operator&的左操作数必须是integral类型,而不是floating_point。这样做。

inline bool is_pos_float(float x) {
  return x > 0.0f;
}

编辑。假设OP真正想要的是浮点格式,我认为如果机器是Little Endian,这将有效。

bool high_bit_zero(float x) {
    constexpr unsigned sz = sizeof(float);
    using raw = unsigned char[sz];
    raw *c = reinterpret_cast<raw*>(&x);
    return !((*c)[sz-1] & (1 << 7));
}

答案 1 :(得分:-1)

你打算做什么?使用float变量???

的位

如果您打算确保x为正或零,则解决方案正在使用!(x<0.0f)

float转换为int会导致忽略-1+1之间的小数字,但这些数字也不起作用。

如果你坚持做一些hacky,请看看IEEE-754标准:

#include <iostream>
using namespace std;

static bool is_posz_float(float x)
{
  static_assert(sizeof(float) == 4, "Unexpected type size!");
  union IEEE754{
    float number;
    unsigned char bytes[sizeof(float)];
  };
  IEEE754 a;
  a.number=x;
  return (a.bytes[sizeof(float)-1] & (1 << 7)) == 0;
}

void test(float x)
{
    if(is_posz_float(x))
        cout<<x<<" is a positive number or zero."<<endl;
    else
        cout<<x<<" is a negative number."<<endl;
}


int main() {
    test(0.1f);
    test(0.0f);
    test(3.14f);
    test(-0.11);
    return 0;
}

结果:

0.1 is a positive number or zero.
0 is a positive number or zero.
3.14 is a positive number or zero.
-0.11 is a negative number.