Skip to content

Instantly share code, notes, and snippets.

@dbechrd
Last active February 11, 2020 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbechrd/eabcd9d03122906be6beef889abb0c07 to your computer and use it in GitHub Desktop.
Save dbechrd/eabcd9d03122906be6beef889abb0c07 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <float.h>
#include <math.h>
// Takes a float in the range [-1.0, 1.0] and converts to an int in the range [INT_MIN, INT_MAX]
// NOTE: Floats outside of this range will be clamped
int normalized_ftoi(float f)
{
// Clamp float to [-1.0, 1.0f]
if (f > 1.0f) f = 1.0f;
if (f < -1.0f) f = -1.0f;
f /= 2.0f;
// Calculate range of ints (in a bigger type to prevent overflow), then multiply by float
long long range = (long long)INT_MAX - INT_MIN;
long long lng = (long long)(f * range);
// Clamp the long back into int range to prevent overflow
if (lng < INT_MIN) lng = INT_MIN;
if (lng > INT_MAX) lng = INT_MAX;
// Convert to int
return (int)lng;
}
int normalized_ftoi_test(float f, int expected)
{
int i = normalized_ftoi(f);
printf("%52.10f -> %12d == %12d (%s)\n", f, i, expected, i == expected ? "PASS" : "FAIL");
}
int main(int argc, char *argv[])
{
normalized_ftoi_test(INFINITY, INT_MAX);
normalized_ftoi_test(FLT_MAX, INT_MAX);
normalized_ftoi_test(2.0f, INT_MAX);
normalized_ftoi_test(1.0f, INT_MAX);
normalized_ftoi_test(0.0000000008f, 3);
normalized_ftoi_test(0.0000000006f, 2);
normalized_ftoi_test(0.0000000004f, 1);
normalized_ftoi_test(FLT_MIN, 0);
normalized_ftoi_test(0.0f, 0);
normalized_ftoi_test(-FLT_MIN, 0);
normalized_ftoi_test(-0.0000000004f, -1);
normalized_ftoi_test(-0.0000000006f, -2);
normalized_ftoi_test(-0.0000000008f, -3);
normalized_ftoi_test(-1.0f, INT_MIN);
normalized_ftoi_test(-2.0f, INT_MIN);
normalized_ftoi_test(-FLT_MAX, INT_MIN);
normalized_ftoi_test(-INFINITY, INT_MIN);
return 0;
}
// Output:
// inf -> 2147483647 == 2147483647 (PASS)
// inf -> 2147483647 == 2147483647 (PASS)
// 340282346638528859811704183484516925440.0000000000 -> 2147483647 == 2147483647 (PASS)
// 2.0000000000 -> 2147483647 == 2147483647 (PASS)
// 1.0000000000 -> 2147483647 == 2147483647 (PASS)
// 0.0000000008 -> 3 == 3 (PASS)
// 0.0000000006 -> 2 == 2 (PASS)
// 0.0000000004 -> 1 == 1 (PASS)
// 0.0000000000 -> 0 == 0 (PASS)
// 0.0000000000 -> 0 == 0 (PASS)
// -0.0000000000 -> 0 == 0 (PASS)
// -0.0000000004 -> -1 == -1 (PASS)
// -0.0000000006 -> -2 == -2 (PASS)
// -0.0000000008 -> -3 == -3 (PASS)
// -1.0000000000 -> -2147483648 == -2147483648 (PASS)
// -2.0000000000 -> -2147483648 == -2147483648 (PASS)
// -340282346638528859811704183484516925440.0000000000 -> -2147483648 == -2147483648 (PASS)
// -inf -> -2147483648 == -2147483648 (PASS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment