byte + byte = int… why?

前端 未结 16 2051
长情又很酷
长情又很酷 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:11

    This is because of overflow and carries.

    If you add two 8 bit numbers, they might overflow into the 9th bit.

    Example:

      1111 1111
    + 0000 0001
    -----------
    1 0000 0000
    

    I don't know for sure, but I assume that ints, longs, anddoubles are given more space because they are pretty large as it is. Also, they are multiples of 4, which are more efficient for computers to handle, due to the width of the internal data bus being 4 bytes or 32 bits (64 bits is getting more prevalent now) wide. Byte and short are a little more inefficient, but they can save space.

提交回复
热议问题