This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Bitwise left shift confusion...?

Guru 15580 points

Ok. I'm a bit ashamed to be posting such a trivial problem. But in the essence of saving time....

I would like to create a 32-bit mask variable by using the bitwise left shift operator. Here is my code.

unsigned long mask_variable;

unsigned long shift_value;

mask_variable = 0;

mask_variable |= 1 << shift_value;

Unfortunately, the mask_variable result after using a shift_value of 16 is 1111111100000000 and not 0000000100000000 as I had hoped. Can someone spot what I am doing wrong?

  • Are you using a platform with 16-bit int, by any chance?  "1 << shift_value" will shift the int 1 left by that many bits -- producing another int.  (And if the shift value is at least as large as the value being shifted, you get undefined results. [Edited: Originally I said implementation-defined, which is incorrect, even though most compilers generate something reasonable for the target CPU.])  If you write "1ul << shift_value" it should produce the results you are looking for.

  • Michael,

    Michael P said:
    If you write "1ul << shift_value" it should produce the results you are looking for.

    BINGO!! You win the prize!

    Michael P said:
    Are you using a platform with 16-bit int, by any chance?

    Yes, I am using a C5515. But I thought since I declared both of the variables as unsigned long it would work as expected. I guess the "1" was the culprit.

    THANKS! Good eyes......

  • MikeH said:
    But I thought since I declared both of the variables as unsigned long it would work as expected.

    No.  In C, the type of an arithmetic expression depends strictly on the types of the input values.  The type of the variable is irrelevant until the assignment.

  • Thanks for the clarification.