签名的整数,但是我需要nunsigned整数。我不能简单地提高渴望,因为我还需要将双打转换为未签名的渴望。我发现的唯一方法是转换为字符串,然后转换为未签名的int:
int i;
try {
i = Integer.parseUnsignedInt(Float.toString((float)Math.floor(f)));
} catch (NumberFormatException e) {
i = 0;
}
否,对我来说这似乎太拼凑了。我敢肯定,有一种更好的方法可以做到这一点,但是我似乎找不到在线上的任何东西,而chatgpt只是像往常一样胡说八道。有更好的转换方法吗?
Edit:
0.0f
应该给
0
。
-1.5f
0
。
NaN
0
。
1.7f
应该给1
3e+9f
应给予
-1294967296
1e+12f
应该给0
。
if
语句float
long
int
范围内,请进一步施放至int
。否则结果为0。
private static int convertFloatToUnsignedInt(float f) {
if (f >= 0) {
long asLong = (long) f;
// Within range of unsigned int?
if (asLong < 0x1_0000_0000L) {
return (int) asLong;
}
}
return 0;
}
llet尝试使用您的示例float
值::
float[] exampleFloats = { 0.0f, -0.1f, -1.5f, Float.NaN, 1.7f, 3e+9f, 1e+12f };
for (float exampleFloat : exampleFloats) {
int asInt = convertFloatToUnsignedInt(exampleFloat);
System.out.format(Locale.ENGLISH, "%14.1f -> %10s or %11d%n",
exampleFloat, Integer.toUnsignedString(asInt), asInt);
}
输出为 0.0 -> 0 or 0
-0.1 -> 0 or 0
-1.5 -> 0 or 0
NaN -> 0 or 0
1.7 -> 1 or 1
3000000000.0 -> 3000000000 or -1294967296
999999995904.0 -> 0 or 0
输出显示了转换为相同的
float
的值,无符号的值int
值转换为同一int
double
未签名
long
…但是双重到长时间呢?
double
:转换:
long
也要尝试一下:
BigDecimal
输出:
private static final double MAX_UNSIGNED_LONG_PLUS_ONE
= 2.0 *(((double) Long.MAX_VALUE) + 1);
private static long convertDoubleToUnsignedLong(double d) {
if (d >= 0 && d < MAX_UNSIGNED_LONG_PLUS_ONE) {
return new BigDecimal(d).longValue();
}
return 0;
}
两种转换方法不是100%一致的。您可能可以简化它们以获得更一致的代码。查看代码在线运行
重复链接@anonymous代码在此处在线运行。在上面,我对其代码进行了较小的调整。