简体   繁体   English

将整数发送到fstream时为小端

[英]Sending integer to fstream as little endian

I am writting function for create and save WAV file but I don't know how to send numbers to stream: 我正在编写用于创建和保存WAV文件的函数,但是我不知道如何发送数字以进行流处理:

ofstream file;
file.open("sound.wav");
file << "RIFF";
file << (int) 32;
file << "WAVE";

I am trying to implement this WAVE file structure: https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ 我正在尝试实现此WAVE文件结构: https : //ccrma.stanford.edu/courses/422/projects/WaveFormat/

and problem is here the output is like this: 问题是这里的输出是这样的:

RIFF32WAVE

The streaming operator << does formatted output - it converts values to text. 流操作符<<执行格式化输出-将值转换为文本。 This is not what you want for writing to a binary file format. 这不是您想要写入二进制文件格式的内容。

Instead, you want to use the unformatted output functions: put for single bytes, and write for multiple bytes: 相反,您想使用未格式化的输出函数: put表示单个字节, write表示多个字节:

file.write("RIFF", 4);

// The length field is little-endian, so write the lowest byte first
file.put(length);
file.put(length >> 8);
file.put(length >> 16);
file.put(length >> 24);

file.write("WAVE", 4);

UPDATE: as noted in the comments, you should also open the file in binary mode and inbue it with the classic "C" locale, to prevent anything from messing around with the bytes you write: 更新:如注释中所述,您还应该以二进制模式打开文件,并使用经典的“ C”语言环境来注入文件,以防止任何东西弄乱您写入的字节:

file.open("sound.wav", std::ios_base::out | std::ios_base::binary);
file.imbue(std::locale::classic());

You should open the file in binary output mode and then print into it. 您应该以二进制输出模式打开文件,然后将其打印。

See this question for how to do that. 有关如何操作的信息,请参见此问题

Stream operators is for formatted I/O (Text), not binary. 流运算符用于格式化的I / O(文本),而不用于二进制。 Take a look at the write method instead. 请看一下write方法。 As for the little vs big endian issue, you could simply use the htonl() function provided by your OS. 至于小端与大端的问题,您可以简单地使用操作系统提供的htonl()函数。

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

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