C# bitwise shift on ushort (UInt16)
Asked Answered
P

1

14

I need to perform a bitwise left shift on a 16-bit integer (ushort / UInt16), but the bitwise operators in C# seem to apply to int (32-bit) only. How can I use << on an ushort, or at least get to the same result with a simple workaround?

Protomorphic answered 29/9, 2010 at 7:32 Comment(0)
S
19

Cast the resulting value back into ushort after shifting:

ushort value = 1;
ushort shifted = (ushort)(value << 2);
Sandeesandeep answered 29/9, 2010 at 7:34 Comment(4)
will value be implicitly converted to uint for the << operator?Cottonweed
almost embarrassing, so simply this was :) I did almost the same, but forgot the brackets around (value << 2)Protomorphic
@xtofl, value will be implicitly converted to int.Sandeesandeep
@xtofl, int as @Sandeesandeep says. Note also that in this case, and many similar cases, the result will be the same either way.Battledore

© 2022 - 2024 — McMap. All rights reserved.