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.