为什么使用unsigned chars写入二进制文件?为什么不应该使用流操作符来写入二进制文件? [英] Why use unsigned chars for writing to binary files? And why shouldn't stream operators be used to write to binary files?

查看:210
本文介绍了为什么使用unsigned chars写入二进制文件?为什么不应该使用流操作符来写入二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的第一个问题是,为什么习惯使用无符号字符以二进制模式写入文件?在我看到的所有例子中,在写入二进制文件之前,任何其他数值都被转换为unsigned char。

My first question is, why is it customary to use unsigned chars for writing to files in binary mode? In all of the examples I have seen, any other numerical value is casted to unsigned char before writing to the binary file.

我的第二个问题是,使用什么是如此糟糕流操作符写入二进制文件?我听说read()和write()运算符最适合写入二进制文件,但我真的不明白为什么会这样。如果我首先将值转换为unsigned char,使用流操作符写入二进制文件对我来说很好。

My second question is, what's so bad about using stream operators to write to binary files? I've heard that read() and write() operators are best used for writing to binary files, but I don't really understand why that's the case. Using stream operators to write to binary files works fine for me IF I first cast the value to unsigned char.

float num = 500.5;
ostream file("file.txt", ios::binary);

file << num  // results in gibberish when I try to read the file later
file << (unsigned char)num  // no problems reading the file with stream operators

提前致谢。

推荐答案

chars 是C / C ++中的最小类型(根据定义, sizeof(char)== 1 )。它是将对象视为字节序列的常用方法。 unsigned 用于避免签名的arithmethic妨碍,并且因为它最好代表二进制内容(0到255之间的值)。

chars are the smallest type in C/C++ (by definition, sizeof( char ) == 1). Its the usual way to see objects as a sequence of bytes. unsigned is used to avoid signed arithmethic to get in the way, and because it best represents binary contents (a value between 0 and 255).

要对二进制文件进行操作,流提供读取写入函数。格式化插入和提取功能。它只是偶然地为你工作,例如,如果你输出一个整数<<那么它实际上会输出整数值的文本表示而不是其二进制表示。在您提供的示例中,在输出之前将float转换为unsigned char,实际将实数值转换为小整数。当你尝试从文件中读取浮点数时会得到什么?

To operate on binary files, streams provide the read and write functions. The insertion and extraction functionality is formatted. It's working for you just by chance, for instance if you output an integer with << then it will actually output the textual representation of the integer value and not its binary representation. In your provided example, you cast a float to an unsigned char before outputing, actually casting the real value to a small integer. What do you get when you try to read the float back from the file?

这篇关于为什么使用unsigned chars写入二进制文件?为什么不应该使用流操作符来写入二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆