Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

right shifting on non integer types numbers

Tags:

c++

bit-shift

i have following code

#include <iostream>
using namespace std;
int main(){

float f=56.34f;
double d=12.34101;
cout<<(f>>1.0)<<endl;
cout<<(d>>1.0)<<endl;


return 0;
}

but it doesn't work and there is this error:

In function 'int main()': Line 7: error: invalid operands of types 'float' and 'double' to binary 'operator>>' compilation terminated due to -Wfatal-errors.

Is here allowed right shifting in C/C++ compiler? I am using visual studio 2010.

like image 994
dato datuashvili Avatar asked Nov 14 '10 16:11

dato datuashvili


People also ask

How do you shift a number right?

When shifting right with a logical right shift, the least-significant bit is lost and a 0 is inserted on the other end. For positive numbers, a single logical right shift divides a number by 2, throwing out any remainders.

How do you shift binary numbers to the right?

To divide a number, a binary shift moves all the digits in the binary number along to the right and fills the gaps after the shift with 0: to divide by two, all digits shift one place to the right. to divide by four, all digits shift two places to the right.

Is zero fill right shift?

Bitwise Zero Fill Right Shift Operator shifts the bits of the number towards the right a specified n number of positions. The sign bit filled with 0's. The symbol >>> represents the Bitwise Zero Fill Right Shift Operator.

How do you shift a number to the right in Java?

Java supports two types of right shift operators. The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand.


2 Answers

That's because, until C++ gets ported to quantum computers, you can't shift by half a bit.

In other words, it makes no sense for the bitshift operator >> to support floating-point operands. Yet.

like image 183
Frédéric Hamidi Avatar answered Oct 10 '22 20:10

Frédéric Hamidi


You cannot shift non-integral types. It is illegal in C++.

If you are looking to multiply or divide by powers of two, then just do that. Shifting doesn't work like that on floating point numbers due to the way they are represented.

If you actually do want to shift the bit pattern of a float, then you'll need to do some casting, or use a union.

union
{
  float f;
  int i;
} u;
u.f = 56.34f;
u.i >>= 1;
cout << u.f << endl;

But the value you get out is totally meaningless (you aren't dividing by 2).

like image 21
Peter Alexander Avatar answered Oct 10 '22 21:10

Peter Alexander