Skip to content

Instantly share code, notes, and snippets.

@jnorthrup
Last active September 25, 2024 16:19
Show Gist options
  • Save jnorthrup/819430c1673511b793569e2465249f09 to your computer and use it in GitHub Desktop.
Save jnorthrup/819430c1673511b793569e2465249f09 to your computer and use it in GitHub Desktop.
Float32ToInt32Converter
public class Float32ToInt32Converter {
public static int convertFloat32ToInt32(float f) {
if (f == 0.0f) return 0;
int bits = Float.floatToRawIntBits(f);
int sign = (bits >>> 31) & 0x1;
int exponent = (bits >>> 23) & 0xFF;
int mantissa = bits & 0x7FFFFF;
if (exponent == 0xFF) {
return mantissa == 0 ? (sign == 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE) : 0;
}
int adjustedExponent = exponent - 127;
int result = 0x800000 | mantissa;
if (adjustedExponent > 7) {
return sign == 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
} else if (adjustedExponent >= -23) {
result = adjustedExponent >= 0 ? result << adjustedExponent : result >>> -adjustedExponent;
} else {
return sign == 0 ? 0 : -1;
}
return sign == 1 ? -result : result;
}
public static void main(String[] args) {
float[] testValues = {0.0f, -0.0f, 1.0f, -1.0f, 1.5f, -1.5f,
Float.MAX_VALUE, Float.MIN_VALUE,
Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY,
Float.NaN};
for (float value : testValues) {
int result = convertFloat32ToInt32(value);
System.out.printf("Float: %f, Int: %d%n", value, result);
}
}
}
Float: 0.000000, Int: 0
Float: -0.000000, Int: 0
Float: 1.000000, Int: 8388608
Float: -1.000000, Int: -8388608
Float: 1.500000, Int: 12582912
Float: -1.500000, Int: -12582912
Float: 340282346638528860000000000000000000000.000000, Int: 2147483647
Float: 0.000000, Int: 0
Float: Infinity, Int: 2147483647
Float: -Infinity, Int: -2147483648
Float: NaN, Int: 0
Process finished with exit code 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment