I'm trying to find a way to check if a floating point number is negative without branching.
float a = -0.5;
int getSignOfa= *(int*)&a >> 31; //type-pun to int and get signed bit;
Is this a safe way of checking the signed bit of a float?
I'm trying to find a way to check if a floating point number is negative without branching.
float a = -0.5;
int getSignOfa= *(int*)&a >> 31; //type-pun to int and get signed bit;
Is this a safe way of checking the signed bit of a float?
Since C99, you can use signbit(x)
as defined in math.h
to get the sign bit of a floating point number. It returns 0 if x
is positive (sign bit not set) and nonzero if negative (sign bit is set).
You may use copysign()
functions available in math.h
to get the sign of float
number.
float sign = copysign(1, float_num);
Value of sign
is going to be +1
or -1
depending upon the type of input.