Why do I have to cast 0 (zero) when doing bitwise operations in C#? -


i using following code sign extend 12 bit value unpacked 1.5 bytes 16 bits:

word[0] |= ((word[0] & 0x800) != 0 ? (int16)(-4096) : (int16)0); 

if don't cast last 0 int16 following complaints compiler:

warning 1   bitwise-or operator used on sign-extended operand; consider casting smaller unsigned type first error   2   cannot implicitly convert type 'int' 'short'. explicit conversion exists (are missing cast?) 

why this? understand c# converts int when doing bitwise operations, integer constants automatically given right type. if assign 0 float don't have cast float first, example. i'm c programmer, please keep in mind when answering :-)

the types of integer literals in c# types int, uint, long, , ulong (c# language specification, version 5, section 2.4.4.2). literal (such 0) have type inferred 1 of 4 (and without indications, it's int).

so, why does:

short s = 0; 

work? due implicit constant expression conversions (section 6.1.9):

a constant-expression (§7.19) of type int can converted type sbyte, byte, short, ushort, uint, or ulong, provided value of constant-expression within range of destination type.

but, we're working here isn't constant expression. of conventional c# typing rules come play; when analyzing conditional operator (section 7.14), types are:

bool ? short : int; 

and compiler (without being able use above constant-expression rule) decides type of expression int, since short may implicitly converted int, not vice-versa.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -