1

I have a binary file that contains n single-precision values. I know that the format used when writing data was big-endian. When I read in the data into a float vector ('mainvector' in the code below), by default, the data is read in according to little-endian format. I use the following to read data:

ifstream inputfile("filepath",ifstream::in|ifstream::binary)
inputfile.read(reinterpret_cast<char*>(&mainvector[0]), n*4);
inputfile.close()

There is a lot of discussion on endianness and conversion on stackoverflow itself. However, this is the first time I have to deal with the endianness issue and all the information available is a bit overwhelming. In the process I learned that the bytes are reversed (big vs. little endian).

Is there a one-liner that I can incorporate to change the default little-endian treatment of my binary data to big-endian, or post-process my mainvector in order to get the original data ? or would I need to manually reverse byte-order of each of the n values ?

UPDATE: It appears that there is no one-liner for this. Individually changing the byte order is the way to do it! How to do that is discussed here by Mats and elsewhere (e.g. here).

4

2 回答 2

1

您将需要单独反转每个值。所以这样的事情会起作用:

#include <iostream>
#include <fstream>

int main()
{
    const int n = 34;
    float mainvector[n];

    std::ifstream inputfile;

    for(int i = 0; i < n; i++)
    {
    unsigned char temp[sizeof(float)];
    inputfile.read(reinterpret_cast<char*>(temp), sizeof(float));
    unsigned char t = temp[0];
    temp[0] = temp[3];
    temp[3] = t;
    t = temp[1];
    temp[1] = temp[2];
    temp[2] = t;
    mainvector[i] = reinterpret_cast<float&>(temp);
    }
}

您也许可以使用某种形式的内置函数来交换订单,但这将使其特定于编译器......

于 2013-09-29T18:22:52.033 回答
0

Unix 系统有这方面的例程(其他系统也有)。代码显示在这个答案中。您的编译器必须支持类型别名(以便对 float 的引用可以转换为对 int 的引用,反之亦然)。

于 2013-09-29T23:25:07.237 回答