据我所知,
此外,请看一下我找到的“bmp 文件图像阅读器”库中的这个函数:
为什么
read()
和 write()
存在的目的是为了我们能够直接从文件中读取和写入字节,我曾被教导过,在 c++ 中,byte
的等效类型是 unsigned char
,那么为什么它们要将 char
指针作为参数呢?此外,请看一下我找到的“bmp 文件图像阅读器”库中的这个函数:
bool BMPImage::readInfo()
{
//...
//read bmp and dib headers
unsigned char header[28] = {0};
_ifs->read((char*)header, 28);
_width = *(int*)&header[18]; //width is located in [18] and is 4 bytes size
_height = *(int*)&header[22]; //height is located in [22] and is 4 bytes size
_bpp = (unsigned char) *(short*)&header[28]; //bpp is located in [28] and is 2 bytes size
_channels = _bpp / 8; //set num channels manually
//...
为什么
_ifs->read()
这行代码能够正常工作?将unsigned char强制转换为char会导致数据丢失,不是吗?
char
和unsigned char
的大小相同,都是 1 字节。唯一的区别在于有无符号:unsigned char
总是 > 0;而普通的char
可以是有符号的(但不一定)。 - Ben Steffanchar
和unsigned char
之间没有实际区别。但由于大多数人在程序中使用char
,因此 API 接受最常用的类型是很自然的事情。 - SergeyA