if statementI am converting the comments by @Anonymous and the code they link to to this answer. If your float is >= 0, cast to long first, and if within the unsigned int range, cast further to int. Otherwise the result is 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;
}
Let’s try it with your example float values:
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);
}
Output is
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
The output shows the float value, the unsigned int value converted to and the signed value of the same int.
double to unsigned long… but what about double to long?
For the case of converting double to unsigned long using the same criteria, you may convert via 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;
}
Trying this out too:
double[] exampleDoubles = { 0.0, -1.5, Double.NaN, 1e+19, 1e+20 };
for (double exampleDouble : exampleDoubles) {
long asLobg = convertDoubleToUnsignedLong(exampleDouble);
System.out.format(Locale.ENGLISH, "%23.1f -> %20s or %20d%n",
exampleDouble, Long.toUnsignedString(asLobg), asLobg);
}
Output:
0.0 -> 0 or 0
-1.5 -> 0 or 0
NaN -> 0 or 0
10000000000000000000.0 -> 10000000000000000000 or -8446744073709551616
100000000000000000000.0 -> 0 or 0
The two conversion methods are not 100 % consistent. You may be able to streamline them a bit for more consistent code.
Repeating the link by @Anonymous the code is running online here. In the above I have made very minor adjustments to their code.