Left shift Float type

2020-03-03 05:17发布

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?

7条回答
我想做一个坏孩纸
2楼-- · 2020-03-03 05:56

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.

查看更多
Melony?
3楼-- · 2020-03-03 06:00

Floating point numbers don't have bits at the level of value-representation, which is why you can't apply bitwise operations to them.

See this answer for more information.

查看更多
戒情不戒烟
4楼-- · 2020-03-03 06:02

You'd have to transform the float to something else first. Such as:

float f = 128;
f = (float) (((int) f) << 1 );

And in the above, f should be 256.0.

Now obviously this is problematic if you start with 128.4 as the cast will drop the .4. You may not want to be using a float in first place.

查看更多
我命由我不由天
5楼-- · 2020-03-03 06:06

Since the left shift operator is defined as multiplication by a power of 2, it makes perfect sense for floating point types. However, the C language does not define its use, so instead you have to use the scalbn function or similar.

查看更多
放荡不羁爱自由
6楼-- · 2020-03-03 06:06

You cannot left shift objects of float type.

C says the operands of the bitwise shift operators shall have integer type.

查看更多
孤傲高冷的网名
7楼-- · 2020-03-03 06:09

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

查看更多
登录 后发表回答