Reputation: 135
I need to create a function abs for float with bitwise operators, this function return float value.
I can't use <
or >
.
I try this
(float)((int)f ^ ((int)f>>31)) - ((int)f>>31)
but for -2.5
value I get 2.0
, it's not correct.
Can you help me?
Upvotes: 0
Views: 514
Reputation: 533820
You can do this
float abs = Float.intBitsToFloat(Float.floatToIntBits(x) & 0x7FFFFFFF);
Upvotes: 3
Reputation: 4869
The most significant bit of a float is the sign bit. So... you should be able to use the bitwise & operator to clear that bit to get the absolute value.
Use this as your mask to bitwise and with your value:
0x7fffffff
Upvotes: 2