我的功能:
void output(int word)
{
file << putchar((word >> 24) & 0xff);
file << putchar((word >> 16) & 0xff);
file << putchar((word >> 8) & 0xff);
file << putchar(word & 0xff);
}
其中"file"使用 fstream 将二进制文件从 putchar 输出到名为“binary.bin”的文件中。 当“word”为1时,binary.bin的二进制表示为00110000 00110000 00110000 00110001。
应该是00000000 00000000 00000000 00000001。(注:一个字是32位)
00110000 00110000 00110000 00110001 是 0001 (30 30 30 31) 的 ascii 表示。
出了什么问题?
最佳答案
问题是operator<<
.流插入运算符旨在将其输入转换为文本格式并将格式化的文本传递给流。
file << putchar((word >> 24) & 0xff);
^^----> this is the problem.
您将需要使用不执行翻译的流方法,例如 std::ostream::put
或 std::ostream::write
.
另外,请注意 putchar
函数将其参数写入控制台并在成功时返回参数。
参见 explanation of putchar.
关于C++使用 "putchar"以二进制形式输出一个字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26303013/