浮点数的字节序 [英] Endianness for floating point

查看:416
本文介绍了浮点数的字节序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 std :: fstream std :: ios :: binary ) $ c>-包括整数和浮点值。虽然我的代码可以在自己的体系结构上运行,但我无法确保它是可移植的,也就是说,仍然可以从具有不同字节序的计算机上正确读取在我的计算机上写入的二进制文件。所以我的想法是,我将在二进制文件的第一个字节中添加一个值,该值将指示文件的字节序。

I'm writing and reading binary data (std::ios::binary) in C++ using std::fstream - this includes integer and floating point values. While my code works on my own architecture, I wan't to make sure, that it's portable and i.e. binary files written on my machine shall still be read properly of an machine with different endianness. So my idea was that I will add in the binary file at first byte a value which will indicate the endianness of the file.

由于不能保证,整数和浮点数相同,我需要分别获取两种数据类型的信息。尽管使用指针算法获得整数的字节性非常简单,但是我迷失了如何在运行时获得浮点数的字节性。知道吗?

As there is no guarantee, that endianness of integer and floating points are the same, I need to get the information for both datatypes separately. While getting the endianess for integer was rather simple with pointer arithmetic, I'm lost how to get the endianess for float at runtime. Any idea?

我的代码如下:

#include <cstdint>

#define INT_LITTLE_ENDIAN     0x01u
#define INT_BIG_ENDIAN        0x02u
#define FLOAT_LITTLE_ENDIAN   0x04u
#define FLOAT_BIG_ENDIAN      0x08u

uint8_t getEndianess(){
  uint8_t endianess = 0x00;
  uint16_t integerNumber = 0x1;
  uint8_t *numPtr = (uint8_t*)&integerNumber;
  if (numPtr[0] == 1) {
    endianess |= INT_LITTLE_ENDIAN;
  }else {
    endianess |= INT_BIG_ENDIAN;
  }
  /* TODO: check endianess for float */
  return endianess;
}


推荐答案

好吧,除了字节序,您也有可能使用非IEEE-754格式,但这确实很少见。

Well, besides just endianness, you also have the potential for non-IEEE-754 formats, but that is admittedly rare.

如果您可以假定IEEE-754二进制文件,那么几乎可以肯定使用相同的格式endianness作为整数,但是您可以通过使用浮点数来方便地进行检查,该浮点数是2的负幂(例如-1.0),该浮点值的MSbyte值将为非零(包含符号和指数的一部分),并且为零

If you can assume IEEE-754 binary, then it almost certainly uses the same endianness as integers, but you can readily check by using a floating point value that is a negative power of two (such as -1.0), which will have a non-zero MSbyte (containing the sign and part of the exponent) and a zero LSbyte (containing the least significant mantissa bits).

float floatNumber = -1.0;
uint8_t *numPtr = (uint8_t*)&floatNumber;
if (numPtr[0] == 0) {
  endianess |= FLOAT_LITTLE_ENDIAN;
} else {
  endianess |= FLOAT_BIG_ENDIAN;
}

这篇关于浮点数的字节序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆