byte + byte = int… why?

前端 未结 16 2296
长情又很酷
长情又很酷 2020-11-22 04:33

Looking at this C# code:

byte x = 1;
byte y = 2;
byte z = x + y; // ERROR: Cannot implicitly convert type \'int\' to \'byte\'

The result of

16条回答
  •  心在旅途
    2020-11-22 05:24

    This is for the most part my answer that pertains to this topic, submitted first to a similar question here.

    All operations with integral numbers smaller than Int32 are rounded up to 32 bits before calculation by default. The reason why the result is Int32 is simply to leave it as it is after calculation. If you check the MSIL arithmetic opcodes, the only integral numeric type they operate with are Int32 and Int64. It's "by design".

    If you desire the result back in Int16 format, it is irrelevant if you perform the cast in code, or the compiler (hypotetically) emits the conversion "under the hood".

    For example, to do Int16 arithmetic:

    short a = 2, b = 3;
    
    short c = (short) (a + b);
    

    The two numbers would expand to 32 bits, get added, then truncated back to 16 bits, which is how MS intended it to be.

    The advantage of using short (or byte) is primarily storage in cases where you have massive amounts of data (graphical data, streaming, etc.)

提交回复
热议问题