简体   繁体   中英

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:

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/

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:

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:

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. Take a look at the write method instead. As for the little vs big endian issue, you could simply use the htonl() function provided by your OS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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