简体   繁体   English

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

[英]How Do You Write 16 Bit Integers To File?

Using C++, Windows 7, Intel CPU. 使用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. 我想做的是将浮点值[-1,1]映射到16位带符号的值,并将其写入文件。 The most obvious thing to do seems to be to multiply the float values by 32768 (2^16 / 2) and then simply write them. 最显而易见的事情似乎是将float值乘以32768(2 ^ 16/2),然后简单地将它们写入。 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. 在我看来,它好像将每个int16_t值的数字都写为自己的字节一样。 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: 这是由于两个错误:首先是当您打开一个没有指定openmode的文件时,该文件以文本模式打开,并且您希望它是二进制的:

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: 您需要write数据:

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: 如果要写入实际字节,请使用未格式化的 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. 并且您需要使用write函数来写入值。

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

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

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