Skip to content

Instantly share code, notes, and snippets.

@yinyin
Last active August 13, 2017 17:27
Show Gist options
  • Save yinyin/a9607f4104f4c1b15143df03ade16d15 to your computer and use it in GitHub Desktop.
Save yinyin/a9607f4104f4c1b15143df03ade16d15 to your computer and use it in GitHub Desktop.
Function to convert IEEE-754 float into IBM float for GRIB
#include <endian.h>
#include <stdint.h>
#include <stdio.h>
uint32_t to_grib_float(float r) {
union {
float f;
uint32_t i;
char c[4];
} r_input;
uint32_t v;
uint32_t m;
uint32_t b;
uint32_t a;
uint32_t fin_i;
r_input.f = r;
v = r_input.i;
m = (0x7F800000 & v) >> 23;
b = 0x7FFFFF & v;
if ( (0 != m) && (0 != b) ) {
m++;
b = b| 0x800000;
a = m + 129;
while (0 != (a & 0x3)) {
b = (b >> 1) & 0x7FFFFF;
a++;
}
a = a >> 2;
}
/* printf(">>> 0x%02X 0x%08X 0x%02X 0x%06X.\n", v, (0x80000000 & v), a, b); */
fin_i = (0x80000000 & v) | ((a << 24) & 0x7F000000) | b;
return htobe32(fin_i);
}
/* {{{ for testing */
int main(int argc, char **argv) {
uint32_t v;
v = to_grib_float(-118.625);
printf("> 0x%08X.\n", v);
return 0;
}
/* }}} for testing */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment