Java:字节上的算术运算

编程入门 行业动态 更新时间:2024-10-09 19:14:58
本文介绍了Java:字节上的算术运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的代码怎么了?以下代码适用于整数类型的数据,但不适用于字节类型的数据。

What happened to my code? The following code worked for integer type of data, but couldn't work for byte type of data.

public class Exchange { public static void main(String[] args) { //int a = 23, b = 44; byte a = 23, b = 44; a = a + b; b = a - b; a = a - b; System.out.println("a=" + a + "b=" + b); } }

我知道数据类型字节可以保存数据范围-2 ^(8-1)到-1 + 2 ^(8-1)。但我正在使用23& 44,所以它小于127.

I know that the data-type byte can hold data of the range -2^(8-1) to -1+2^(8-1). But I'm using 23 & 44, so it's less than 127.

这里我收到错误消息不兼容的类型:从int到byte的可能有损转换。

Here I got error message "incompatible types: possible lossy conversion from int to byte".

推荐答案

如果你想对 byte 执行算术运算并将其分配回 byte 变量你应该明确地让编译器知道你知道你正在做什么,否则你将通过转换 int得到你丢失信息的错误(算术运算的结果)到 byte (在左侧)。

If you want to perform an arithmetic operation on byte and assign it back to a byte variable you should explicitly let the compiler know that "you know what you're doing" otherwise you'll get the the error that you're losing information by converting int (the outcome of the arithmetic operation) to byte (on the left side).

要解决此问题,请将算术运算的结果强制转换为byte:

To fix this, cast the outcome of the arithmetic operation back to byte:

byte a = 23, b = 44; a = (byte) (a + b); b = (byte) (a - b); a = (byte) (a - b);

更多推荐

Java:字节上的算术运算

本文发布于:2023-11-30 15:48:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650571.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算术   字节   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!