Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left shift Float type

get a complier error while trying to do

float_val=float_val<<1;

It gives out a error saying "error C2296: '<<' : illegal, left operand has type 'float '"

Can't v left shift float vars? Why is this so?

like image 286
Akash Avatar asked Feb 16 '12 16:02

Akash


3 Answers

You can't left shift float variables, because (a) your FPU generally will not have a barrel shifter exposed to you so physically cannot generate code to do that, and (b) what would it even mean? The underlying bit representation consists of multiple fields with different meanings, do you really want those bits bleeding into each other?

If you want to multiply the number held in that variable by two, you should just do that instead.

If you want to reinterpret the float as some type that left shift makes sense on (e.g. a suitably large unsigned integer type) for some horrible bit hack like Carmack's square root, well, you can do that too, but on modern hardware it is highly unlikely that you really need to: seriously consider if there is a better way to do what you want.

like image 162
moonshadow Avatar answered Nov 17 '22 06:11

moonshadow


Check out the standard function ldexpf if you want to quickly multiply or divide a float by a power of 2. A bit obscure obviously :-).

https://linux.die.net/man/3/ldexpf

like image 5
Aaron Madsen Avatar answered Nov 17 '22 06:11

Aaron Madsen


Shifting floats makes no sense since it's represented as the concatenation of a sign bit, an exponent and a mantissa. Since shifting operation is about shifting bits, it would imply shifting bits from mantissa to exponent and / or to sign bit.

like image 2
Scharron Avatar answered Nov 17 '22 05:11

Scharron