0

Hi,I have a code like this:

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

But after compile, it shows:

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

What's the problem?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
yiyijing
  • 85
  • 4
  • 2
    You need to get a bitwise copy of the floating point `x` as an integer. Floating point values makes no sense in bitwise operations. Also note that your code relies on implementation-specific details of the floating point format. Lastly, if you want to know if a floating point value is not negative, why not simply make that comparison? As in `x >= 0.0f`? – Some programmer dude Feb 08 '18 at 07:50
  • You can't use floats in a bitwise operation would be my first guess. Error message seems pretty clear. – Mad Physicist Feb 08 '18 at 07:52
  • Possible duplicate of [How to perform a bitwise operation on floating point numbers](https://stackoverflow.com/questions/1723575/how-to-perform-a-bitwise-operation-on-floating-point-numbers) – xskxzr Feb 08 '18 at 08:04

2 Answers2

2

The left operand of built-in operator& must be an integral type, not floating_point. Do this instead.

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

Edit. Assuming that what the OP really wants is to muck around in the floating point format, I think this will work if the machine is 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));
}
Jive Dadson
  • 16,680
  • 9
  • 52
  • 65
-1

What do you plan to do? Playing with the bits of a float variable???

If you are planning to make sure x is positive or zero, the solution is using !(x<0.0f).

Converting float to int causes neglecting small numbers between -1 and +1 which does not work too.

If you insist on doing something hacky, have a look at IEEE-754 standard:

#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;
}

The results:

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.
Arash
  • 2,114
  • 11
  • 16