本文介绍了使用类型转换添加字节,Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在字节数组中添加两个值.这是我的代码:

I am trying to add two values in a byte array. This is my code:

byte[] ars = {3,6,9,2,4};
ars[0] = (byte)ars[0] + (byte)ars[4];
System.out.println( ars[0] );

我在编译时遇到此错误:

I get this error on compilation:

Main.java:9: possible loss of precision
found   : int
required: byte
    ars[0] = (byte)ars[0] + (byte)ars[4];
                          ^
1 error

一如既往,非常感谢任何帮助.

Any help is, as always, much appreciated.

推荐答案

关闭,但有点不对.

ars[0] = (byte)(ars[0] + ars[4]);

记住 ars[0]ars[4] 已经是字节了,所以没有必要将它们转换为字节.

keep in mind ars[0] and ars[4] are already bytes, so there is no need to cast them to bytes.

相反,将求和的结果转换为一个字节.

Instead, cast the result of the summation to a byte.

这篇关于使用类型转换添加字节,Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 13:06