在Java中有没有办法将字节类型和浮点类型的值相乘?

Is there a way to multiply a byte type and a float type value in Java?

C++ 代码中我有 unsigned char,如果我将 255(0xff) 值乘以 0.5 我将在我的 java 代码中得到 127.But我不能这样做,因为 byte 已签名。 代码示例:

byte a = (byte) 0xFF;
System.out.println(String.format("0x%02X ", a));
float b = 0.5;
float c = a * b;
System.out.println(String.format("0x%02X ", c)); 

结果会是

0xff
0x00

有没有办法相乘,所以我得到 7fint 127 并将该值存储回byte 类型变量?

byte 类型在 Java 中签名。所以字节 0xFF 表示 -1 而不是 +255。所以 -1 的一半是 -0.5 ...当你转换回一个字节时,它要么是 -1 要么是 0 ...取决于四舍五入。

您可能应该这样做:

byte a = (byte) 0xFF;
float c = Byte.toUnsignedInt(a) * 0.5f;
byte d = (byte) c;

或者,您可以使用整数除法:

byte a = (byte) 0xFF;
int c = Byte.toUnsignedInt(a) / 2;
byte d = (byte) c;

...虽然这会截断为零(这些数字是正数)而不是四舍五入。