如何用c++文件函数读写8位整数单位形式的数据
How to read and write data in 8 bit integers unit form by c++ file functions
是否可以以0到255的整数形式而不是8位字符存储数据?虽然两者是相同的事情,我们如何做到这一点,例如,用write()函数?是否可以直接将任何整数转换为char,反之亦然?像
这样的东西{
int a[1]=213;
write((char*)a,1);
}
和
{
int a[1];
read((char*)a,1);
cout<<a;
}
工作从文件中的相同位置获得213 ?它可能在那台计算机上工作,但它是否可移植,换句话说,它是否适合跨平台项目?如果我使用这一原则为每个游戏关卡创建一个文件格式(将物体的坐标存储在当前关卡的文件中),它是否能够在其他计算机/系统/平台上运行以加载相同的关卡?
您显示的代码将写入a[0]
的对象表示的第一个(最低地址)字节-它可能是也可能不是具有值213
的字节。int
的特定对象表示是实现定义的。
写入一个值为213
的字节的可移植方法是
unsigned char c = a[0];
write(&c, 1);
您的想法是对的,但是还需要一些改进。
{
int intToWrite = 213;
unsigned char byteToWrite = 0;
if ( intToWrite > 255 || intToWrite < 0 )
{
doError();
return();
}
// since your range is 0-255, you really want the low order byte of the int.
// Just reading the 1st byte may or may not work for your architecture. I
// prefer to let the compiler handle the conversion via casting.
byteToWrite = (unsigned char) intToWrite;
write( &byteToWrite, sizeof(byteToWrite) );
// you can hard code the size, but I try to be in the habit of using sizeof
// since it is better when dealing with multibyte types
}
{
int a = 0;
unsigned char toRead = 0;
// just like the write, the byte ordering of the int will depend on your
// architecture. You could write code to explicitly handle this, but it's
// easier to let the compiler figure it out via implicit conversions
read( &toRead, sizeof(toRead) );
a = toRead;
cout<<a;
}
如果你需要最小化空间或者不能承受额外的字符,那么在你的整数中读/写一个特定的位置是绝对可能的。然而,它可能需要在新的头文件中进行链接(例如使用hton/ntons)或烦人(使用platform # definitions)。
它可以工作,但有一些注意事项:
-
使用
reinterpret_cast<char*>(x)
而不是(char*)x
来明确执行通常不安全的强制转换。 -
sizeof(int)
因平台而异,因此您可能希望使用<cstdint>
(如int32_t
)的固定大小整数类型。 -
端序也可能因平台而异,因此在写入文件时应该注意平台字节顺序和交换字节顺序以保持一致的格式。您可以在运行时检测端序并手动交换字节,或者使用htonl和ntohl在主机和网络(大端)字节顺序之间进行转换。
另外,作为一个实际问题,我建议您选择基于文本的格式——它们不那么紧凑,但在出现问题时更容易调试,因为您可以在任何文本编辑器中检查它们。如果您认为加载和解析这些文件太慢,那么可以考虑改用二进制格式。
- 防止主数据类型C++的隐式转换
- 用于访问容器<T>数据成员的正确 API
- 嵌套在类中时无法设置成员数据
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- 使用流处理接收到的数据
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 在cuda线程之间共享大量常量数据
- C++将文本文件中的数据读取到结构数组中
- 如何在C++中序列化结构数据
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 整数数据如何以位为单位存储在内存中?不是右对齐吗?
- 以 ns3 为单位计算数据包接收时间
- 如何在 QLabel 中以像素为单位放置颜色数据
- 文件中数据类型的计数(以C++为单位)
- 解码像 FAST 这样的数据协议的快速方法是什么,其中数据以字节为单位编码,并将位作为存在标志
- 在openMPI中向进程发送数据(以字节为单位)的最佳方式
- 如何用c++文件函数读写8位整数单位形式的数据
- "Float"数据类型的范围值(以C++为单位)