简体   繁体   中英

How Do You Write 16 Bit Integers To File?

Using C++, Windows 7, Intel CPU.

What I want to do is map float values [-1, 1] to 16-bit signed values and write them to a file. The most obvious thing to do seems to be to multiply the float values by 32768 (2^16 / 2) and then simply write them. Here's what happens when I do that:

    std::ofstream outfile(filename.c_str());
    float hypotheticalFloat = 0.25;
    int16_t scaledVal = hypotheticalFloat*32768;
    outfile << scaledVal;

The octal dump command then tells me that I have

    $ od -cd output.pcm
    0000000   8   1   9   2
              12600   12857

Which seems to me like it wrote each of the int16_t value's numbers as its own byte. I would be indebted to anyone who knows what's going on here. I'm at a loss.

It's because of two errors: The first is that when you open a file without a specified openmode , it's opening in text mode, and you want it to be binary:

std::ofstream outfile(filename.c_str(), std::ios::out | std::ios::binary);

The other error is that you use the textual output operator << . You need to write the data:

outfile.write(reinterpret_cast<const char*>(&scaledVal), sizeof scaledVal);

The << operator formats the number and prints a human readable string representation.

If you want to write actual bytes, use unformatted I/O:

outfile.write(reinterpret_cast<char const *>(&scaledVal), sizeof scaledVal);

You might find this template function useful:

template <typename T>
inline void writeRaw(std::ostream &stream, T const &data)
{
    stream.write((char const *) &data, sizeof(data));
}

You need to open the file in "binary" mode.

And you need to use the write function to write the value.

std::ofstream outfile(filename.c_str(), ios:binary);
float hypotheticalFloat = 0.25;
int16_t scaledVal = hypotheticalFloat*32768;
outfile.write((char *)&scaledVal, sizeof(scaledVal)); 

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