如何将16位整数写入文件?

Elw*_*ins 0 c++ windows file

使用C++,Windows 7,Intel CPU.

我想要做的是将浮点值[-1,1]映射到16位有符号值并将它们写入文件.最明显的事情似乎是将浮点值乘以32768(2 ^ 16/2),然后简单地写它们.以下是我这样做时会发生的事情:

    std::ofstream outfile(filename.c_str());
    float hypotheticalFloat = 0.25;
    int16_t scaledVal = hypotheticalFloat*32768;
    outfile << scaledVal;
Run Code Online (Sandbox Code Playgroud)

然后八进制转储命令告诉我,我有

    $ od -cd output.pcm
    0000000   8   1   9   2
              12600   12857
Run Code Online (Sandbox Code Playgroud)

在我看来,它将每个int16_t值的数字写为自己的字节.我会感激任何知道这里发生了什么的人.我不知所措.

Som*_*ude 5

这是因为两个错误:第一个是当你打开没有指定openmode的文件时,它在文本模式下打开,你希望它是二进制的:

std::ofstream outfile(filename.c_str(), std::ios::out | std::ios::binary);
Run Code Online (Sandbox Code Playgroud)

另一个错误是您使用文本输出运算符<<.你需要write的数据:

outfile.write(reinterpret_cast<const char*>(&scaledVal), sizeof scaledVal);
Run Code Online (Sandbox Code Playgroud)