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?
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));
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.