简体   繁体   English

将二进制文件中的小端读取到 C++ 中的整数

[英]reading little endian from binary file into integers in C++

I am parsing a wav file and slowing it down or speeding it up by a given factor.我正在解析一个 wav 文件并按给定因素减慢或加快速度。 So I want to read the sample rate and the byte rate from the wave file header and modify it according to the factor.所以我想从波形文件header中读取采样率和字节率,并根据因子进行修改。 The problem is that they are in little endian.问题是它们是小端的。

In C, I can do this在 C 中,我可以这样做

inline void endian_swap(unsigned int& x)
    {
        x = (x>>24) | 
            ((x<<8) & 0x00FF0000) |
            ((x>>8) & 0x0000FF00) |
            (x<<24);
    } 

and then接着

unsigned int num;
while ( fread(&num, 1, 4,fp) != 0) 
endian_swap(num); 

but how can I do the same in C++?但是我怎样才能在 C++ 中做同样的事情? I have tried我努力了

    int length = 4; 
    my_input_file.read(&num, length);

but it didn't work because the compiler was expecting a char pointer in the first argument.但它不起作用,因为编译器在第一个参数中期望一个 char 指针。 I am using filestreams everywhere in the code and that's why I cannot just use a file pointer and do it the C way.我在代码中的任何地方都使用文件流,这就是为什么我不能只使用文件指针并以 C 方式进行操作。 Any idea how can I do this?知道我该怎么做吗?

Also, Can I use sscanf to read little-endian formatted data from the binary file into an integer directly?另外,我可以使用 sscanf 将二进制文件中的小端格式数据直接读取到 integer 中吗?

In C, I can do this在 C 中,我可以这样做

Problems with your approach are:您的方法存在的问题是:

  1. It only works if bytes have 8 bits.它仅在字节有 8 位时才有效。 This is not guaranteed by the C (nor C++). C(也不是 C++)不保证这一点。
  2. It only works if usigned int has 4 bytes.它仅在usigned int有 4 个字节时才有效。 This is not guaranteed by the C (nor C++) standard. C(也不是 C++)标准不保证这一点。
  3. Swapping should only be done for little endian input if the CPU is natively big endian.如果 CPU 本身是大端,则只应为小端输入进行交换。 This is not guaranteed by the C (nor C++) standard. C(也不是 C++)标准不保证这一点。 Note that x86 is little endian.请注意,x86 是小端。
  4. C doesn't have references. C 没有参考资料。

but how can I do the same in C++?但是我怎样才能在 C++ 中做同样的事情?

Besides the issues above, endian_swap happens to be valid C++.除了上述问题, endian_swap恰好是有效的 C++。

In C++, you can use for example this to read a binary file into memory:在 C++ 中,例如,您可以使用以下命令将二进制文件读入 memory:

std::ifstream is(filename, std::ios::in | std::ios::binary);
std::istreambuf_iterator<char> begin = is;
std::istreambuf_iterator<char> end = {};
std::vector<unsigned char> data(begin, end);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM