有没有一种方法可以在Java中将byte类型和float类型的值相乘?

huangapple go评论76阅读模式
英文:

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

问题

在我的 `C++` 代码中我有一些 `unsigned char`,如果我将值2550xff乘以0.5我会得到127但在我的Java代码中我无法这样做因为`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

有没有办法让我得到 *7f*或者在 `int` 中得到 *127*并将该值重新存储在一个 `byte` 类型的变量中
英文:

In C++ code i have unsigned char's and if I multiply a 255(0xff) value with 0.5 I'll get 127.But in my java code I can't do that because byte is signed.
Code example:

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)); 

And the result would be

0xff
0x00

Is there a way to multiply so I get 7f , or in int 127 and store back that value in a byte type variable?

答案1

得分: 2

byte 类型在Java中是有符号的。因此,字节 0xFF 表示的是 -1 而不是 +255。所以 -1 的一半是 -0.5 ...... 当你转换回 byte 类型时,要么是 -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;

... 不过这会向零截断(这些数是正数),而不是四舍五入。

英文:

The byte type is signed in Java. So the byte 0xFF represents -1 not +255. So half of -1 is -0.5 ... which when you convert back to a byte would be either -1 or 0 ... depending on rounding.

You probably should do something like this:

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

Alternatively, you could use integer division:

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

... though that will truncate towards zero (these numbers are positive) rather than rounding.

huangapple
  • 本文由 发表于 2020年9月17日 08:09:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63929504.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定