Oria Gruber
Oria Gruber

Reputation: 1533

bitwise operand in C simple issue

I have a very simple and short question.

we have this code

void fun( unsigned value )
{ 
   unsigned c, displayMask = 1;  // 1 
   for ( c = 1; c <= 32; c++ ) 
   { 
      putchar( value & displayMask ? '1' : '0' );
      displayMask <<= 1; 
      if ( c % 8 == 0 ) 
         putchar( ' ' );
   } 
   putchar( '\n' ); 
}

This function prints the binary value of any unsigned number, but inverted. meaning if you insert 5 then it will print 101 followed by 29 zeros.

The question is, if we substitute displayMask = 1 for displayMask = 1 << 31 << 1 (where the // 1 note is) what will be the output?

The correct answer is, that it will print 32 zeros no matter what value you inserted. But I don't understand why.

if we wrote displayMask = 1 << 31 << 1 then at first it was 000...1, then we rotated 31 times, so it is now 100...0 and then we rotated again so the 1 returns to the start and we again get 000...1. What is wrong with my logic?

Upvotes: 0

Views: 166

Answers (1)

Tomo
Tomo

Reputation: 3521

<< is not bit rotation but bit shift. Therefore 100...0 << 1 is 0, not 1.

Upvotes: 2

Related Questions