Frage

I am right shifting an unsigned int by 32 but it doesn't affect the number at all, why is it happening?

int main()
{
  unsigned int rnd=2347483648;
  cout<<rnd;
  rnd=rnd>>32;
  cout<<endl<<rnd;
}

When the code runs, it displays rnd twice,showing no affect at all. I believe that after right shifting a 32 bit int, shouldn't it display zero?

War es hilfreich?

Lösung

You are missing an assignment operator - the >> shift operator does not perform the operation "in-place":

rnd = rnd >> 32;

You could also use the compound shift operator, which applies the shift operation and then assigns the result back to the variable:

rnd >>= 32;

However, in both cases, this code results in undefined behaviour, see Shifting a 32 bit integer by 32 bits:

If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

So you could get any result from that operation.

Andere Tipps

Shifting by the number of bits in the promoted operand type, or more, gives undefined behaviour. unsigned int is typically 32 bits, so that typically applies when shifting by 32 or more bits as you do here.

This is because different processors behave in different ways when a shift overflows, and the language designers didn't want to prevent implementations from using the processor's built-in shift instruction by specifying a particular behaviour.

The bit-shift operator doesn't modify the original data. It simply returns a modified copy.

I think this is what you meant to do:

rnd = rnd >> 32;

Assuming your unsigned int is 32-bits in size though, that's not really a useful operation to do.

you foget to assign the value to rnd

rnd = rnd>>32

You forgot to assign the result:

rnd = rnd >> 32;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top