简体   繁体   English

char *和unsigned char * cast

[英]char* and unsigned char* casting

I need to read and write binary data in my program. 我需要在程序中读写二进制数据。 After doing a little research, it seemed like an unsigned char array might be a good choice to store the data. 在做了一些研究之后,似乎无符号的char数组可能是存储数据的不错选择。

I open the file in binary mode using the ios::binary flag, but when I go to read or write, the ifstream::read() and ofstream::write() functions are expecting a char* and const char*. 我使用ios :: binary标志以二进制模式打开文件,但是当我去读或写时,ifstream :: read()和ofstream :: write()函数需要char *和const char *。

So, I have to cast my unsigned char* to a char* every time I want to read or write. 因此,每次我想要读或写时,我都必须将我的unsigned char *转换为char *。

I don't think this will make any difference but I'm starting to wonder if I should just use a regular char array to store the data instead. 我不认为这会有任何区别,但我开始怀疑我是否应该使用常规字符数组来存储数据。 I have seen people use both char and unsigned char arrays for this purpose and I don't fully understand the difference. 我见过人们为此目的使用char和unsigned char数组,我不完全理解它们的区别。

Let's say I have 2 arrays: 假设我有2个数组:

char a[20];
unsigned char b[20];

Now I open a file in binary mode and read: 现在我以二进制模式打开文件并阅读:

file.read(a, 20);
file.read((char*)b, 20);

Now I want to write this data to a new file so I open in binary mode again: 现在我想将这些数据写入一个新文件,所以我再次以二进制模式打开:

newfile.write(a, 20);
newfile.write((char*)b, 20);

What's the difference? 有什么不同? Am I better off just using a char array instead of an unsigned char array for binary data? 我最好只使用char数组而不是二进制数据的unsigned char数组?

After doing a little research, it seemed like an unsigned char array might be a good choice to store the data. 在做了一些研究之后,似乎无符号的char数组可能是存储数据的不错选择。

IMO, you could directly store your required structure. IMO,您可以直接存储您所需的结构。 Just be sure it is not platform dependent: eg use int32_t instead of int ( C++11 ) 请确保它不依赖于平台:例如,使用int32_t而不是intC++11

struct A{
    ...
};
A a;
file.write(&a, sizeof(a));

For the difference between char and unsigned char, it really depends on you. 对于char和unsigned char之间的区别,它实际上取决于你。 But you must be coherent: 但你必须连贯一致:

unsigned char[]...
file.write((unsigned char*)b, 20);

or 要么

char[]...
file.write((char*)b, 20);

A signed char is typically considered to hold textual data, while an unsigned char represents a byte, not necessarily of ASCII value. 带符号的char通常被认为是保存文本数据,而unsigned char表示一个字节,不一定是ASCII值。 The convention then is to use unsigned char for binary data, as whether char is signed or not is implementation dependent. 然后,惯例是对二进制数据使用unsigned char,因为char是否已签名是依赖于实现的。

The data type you choose for your data should influence what functions you use, rather than the other way around. 您为数据选择的数据类型应该影响您使用的功能,而不是相反。

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

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