两个字节相乘 [英] Multiplying two bytes

查看:541
本文介绍了两个字节相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释我为什么不能以这种方式将两个字节相乘吗?

Can somebody explain me why I can't to multiply two bytes in this way?

byte a = 1;
byte b = 1;
byte c = a*b;

byte a = 1;
byte b = 1;
short c = a*b;

为什么我必须这样做?

Why I have to do that in this way?

byte a = 1;
byte b = 1;
byte c = (byte)(a*b);

byte a = 1;
byte b = 1;
int/double/float/long c = a*b;


推荐答案

使用 byte进行数学运算时 s,按照JLS,第5.6.2节


当运算符时将二进制数值提升应用于一对操作数,每个操作数必须表示一个可转换为数值类型的值,以下规则适用:

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:


  1. 如果任何操作数是引用类型,则将对其进行装箱转换(第5.1.8节)。

  1. If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

Wilding原语转换(§5.1.2)用于转换以下规则指定的一个或两个操作数:

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:


  • 如果有一个操作数

  • If either operand is of type double, the other is converted to double.

否则,如果其中一个操作数为float类型,则另一个转换为float。

Otherwise, if either operand is of type float, the other is converted to float.

否则,如果其中一个操作数的类型为long,则另一个将转换为long。

Otherwise, if either operand is of type long, the other is converted to long.

否则,两个操作数都将转换为键入int


(强调我的)

这会迫使您分配至少与 int 或投射回 byte

That forces you to assign to a type that is at least as wide as int or to cast back to byte.

这篇关于两个字节相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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