Search code examples
c#bit-shift

Shifting and negating sBytes producing different type promotions


I have my sbyte (41) which is 101001 in binary then I shift It twice to the left and It becomes -92 which is 1111111110100100 in binary meaning that It becomes a short.

But I know that whenever a positive sbyte is negated, It is promoted to Int which is demonstrated in the last 3 lines below. the 92 becomes 11111111111111111111111110100100 in binary when negated.

could you please tell me why didn't the 41 become an int too when It was shifted to the left?

    sbyte ehfveriuvhie1 = 41;
    Console.WriteLine(ehfveriuvhie1 + "\n" + Convert.ToString(ehfveriuvhie1, 2));
    ehfveriuvhie1 <<= 2;
    Console.WriteLine(ehfveriuvhie1 + "\n" + Convert.ToString(ehfveriuvhie1, 2));
    sbyte wrgwaefjvbh= 92;
    Console.WriteLine(-wrgwaefjvbh + "\n" + Convert.ToString(-wrgwaefjvbh, 2));
    Console.WriteLine(wrgwaefjvbh + "\n" + Convert.ToString(wrgwaefjvbh, 2));

Solution

  • If you only shifted it to the left, it would have become an int. That's written ehfveriuvhie1 << 2.

    But you have used <<= which means "shift and then store it back into the original variable", and that variable is type sbyte, which is why the final result is sbyte once again.