How do I handle byte order differences when reading/writing floating-point types in C?

后端 未结 6 1676
生来不讨喜
生来不讨喜 2020-12-03 11:56

I\'m devising a file format for my application, and I\'d obviously like for it to work on both big-endian and little-endian systems. I\'ve already found working solutions fo

6条回答
  •  春和景丽
    2020-12-03 12:46

    Floating point values use the same byte order as integral values imho. Use an union to overlap them with the respective integral counterpart and use the common hton functions:

    float htonf(float x) {
       union foo {
         float f;
         uint32_t i;
       } foo = { .f = x };
    
       foo.i = htonl(foo.i);
       return foo.f;
    }
    

提交回复
热议问题