将 IEEE-754 16 位浮点数打包为 16 位无符号 integer，同时保留顺序

[英]Packing an IEEE-754 16-bit float to a 16-bit unsigned integer while preserving order

``````// Assumes same endian for FP and integers
#include <float.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>

// Assumes same endian for FP and integers
unsigned float_to_sequence(float f) {
union {
float f;
int32_t i;
uint32_t u;
} x = {.f = f};
if (x.i < 0) {
x.u = -x.u;
} else {
x.u |= 0x80000000;
}
return x.u;
}
``````

``````void test(float f) {
printf("%+-20a %+-18.9e ", f, f);
printf("0x%08X\n", float_to_sequence(f));
}

int main(void) {
float f[] = {-INFINITY, -FLT_MAX, -1.0, -FLT_TRUE_MIN, -0.0, //
0.0, FLT_TRUE_MIN, 1.0, FLT_MAX, INFINITY};
size_t n = sizeof f / sizeof f[0];
for (size_t i = 0; i < n; i++) {
test(f[i]);
}
}
``````

Output

``````-inf                 -inf               0x00800000
-0x1.fffffep+127     -3.402823466e+38   0x00800001
-0x1p+0              -1.000000000e+00   0x40800000
-0x1p-149            -1.401298464e-45   0x7FFFFFFF
-0x0p+0              -0.000000000e+00   0x80000000
+0x0p+0              +0.000000000e+00   0x80000000
+0x1p-149            +1.401298464e-45   0x80000001
+0x1p+0              +1.000000000e+00   0xBF800000
+0x1.fffffep+127     +3.402823466e+38   0xFF7FFFFF
+inf                 +inf               0xFF800000
``````