字节+字节= INT ......为什么? [英] byte + byte = int... why?

查看:149
本文介绍了字节+字节= INT ......为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看着这个C#code:

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 any math performed on byte (or short) types is implicitly cast back to an integer. The solution is to explicitly cast the result back to a byte:

byte z = (byte)(x + y); // this works

我想知道是什么原因?它是建筑?哲学?

What I am wondering is why? Is it architectural? Philosophical?

我们有:


  • INT + INT = INT

  • + =

  • 浮动 + 浮动 = 浮动

  • 双击 + 双击 = 双击

  • int + int = int
  • long + long = long
  • float + float = float
  • double + double = double

那么,为什么不:


  • 字节 + 字节 = 字节

  • + =

  • byte + byte = byte
  • short + short = short?

一点背景:我的小数目执行计算的一个长长的清单(即< 8),并存储在一个大阵的中间结果。使用的字节数组的(而不是一个int数组)的更快的(因为缓存命中)。但是,大量的字节铸件s到了code $ P $垫使其成为更不可读。

A bit of background: I am performing a long list of calculations on "small numbers" (i.e. < 8) and storing the intermediate results in a large array. Using a byte array (instead of an int array) is faster (because of cache hits). But the extensive byte-casts spread through the code make it that much more unreadable.

推荐答案

您code段第三行:

byte z = x + y;

其实就是

byte z = (int) x + (int) y;

因此​​,对字节没有+操作,字节是先投以整数和两个整数相加的结果是(32位)整数。

So, there is no + operation on bytes, bytes are first cast to integers and the result of addition of two integers is a (32-bit) integer.

这篇关于字节+字节= INT ......为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆