Why are there no arithmetic operators (+,-,*,/,%) for 8 and 16 bit integers in C#?
本问题已经有最佳答案,请猛点这里访问。
当我知道C中8位和16位整数没有算术运算符
以下代码无法编译。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class Program { static void With16Bit() { short a = 1; short b = 2; short c = a + b; Console.WriteLine(c); } static void With8Bit() { byte a = 1; byte b = 2; byte c = a + b; Console.WriteLine(c); } static void Main(string[] args) { With8Bit(); With16Bit(); } } |
为什么C设计师会这么做?他们对此有何考虑?
有int8,int16的算术公式;但是结果是int32,所以你必须强制转换:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class Program { static void With16Bit() { short a = 1; short b = 2; short c = (short) (a + b); // <- cast, since short + short = int Console.WriteLine(c); } static void With8Bit() { byte a = 1; byte b = 2; byte c = (byte) (a + b); // <- cast, since byte + byte = int Console.WriteLine(c); } static void Main(string[] args) { With8Bit(); With16Bit(); } } |
请记住,当您对
所以:
byte + byte = int
short + short = int
所以如果你想得到实际值,你需要把它转换回去。
试试这个:
1 2 3 4 5 6 7 8 9 | short a = 1; short b = 2; short c =(short) (a + b); Console.WriteLine(c); byte a = 1; byte b = 2; byte c =(byte) (a + b); Console.WriteLine(c); |
来源:
This Behaviour is because the designers have not considered that
byte andshort as actual numbers ,but they have considered them as
only sequence ofbits . so performing arithmetic operations on them
does not make any sense so if that is the case int and long would
serve the purpose.
来自KEK444答案
1 2 3 4 5 | All operations with integral numbers smaller than Int32 are widened 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". |