英文:
Is there a way to multiply a byte type and a float type value in Java?
问题
在我的 `C++` 代码中,我有一些 `unsigned char`,如果我将值255(0xff)乘以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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论