gpt4 book ai didi

c++ - 将 8 个 bool 值保存到 1 个字节

转载 作者:搜寻专家 更新时间:2023-10-31 01:06:11 24 4
gpt4 key购买 nike

我正在编写一个程序,将一个大的 bool 区域(通常大约 512*512 个 bool 变量)写入文件。它会以一种聪明的方式很好地利用它,我正在考虑将它们 8 乘 8 地保存,将这 8 个 bool 值编码为一个字节的形式:

byte = bit0 * boolean0 | ... | bit7 * boolean7

但我不确定如何处理这种转换,尽管我知道逐字节写入和读取文件。

我使用的是 C++,我没有 CS 背景,但这似乎接近序列化的主题,尽管我在这个主题上搜索的所有内容对我来说真的不清楚。它已经被实现了吗,或者有一个非常简单的方法来实现它? (我的意思是尽可能节省 CPU 时间,我的程序每个实例将写入和打开数百万个这样的文件)

干杯。

编辑:

在 Sean 的帮助下(顺便说一句,谢谢你!)我设法取得了一些进展,但它仍然无法正常工作,保存和读取后的数据测试告诉我它已损坏(如未正确重建和所以与初始数据不同)在写作、阅读或两者中的某处...

我的代码可能会有所帮助。

以下是行文:

    typedef char byte;
ofstream ofile("OUTPUT_FILE");
for(int i=0;i<N/8;i++){
byte encoded = 0;
for(int j=0; j<8; j++){
byte bit = (byte)(tab[(i*8+j)/h][(i*8+j)%h]==1);
encoded = (encoded << 1) | bit;
}
ofile << encoded;
}

和阅读线:

for(int i=0;i<N/8;i++){ //N is the total number of entries I have in my final array
temp = ifile.get(); //reading the byte in a char
for(int j=0; j<8; j++){ // trying to read each bits in there
if(((temp >> j) & 1) ? '1' : '0' ){
tab[(i*8+j)/h][(i*8+j)%h]=1;
}
else{
tab[(i*8+j)/h][(i*8+j)%h]=-1; //my programs manipulates +1 (TRUE) and -1 (FALSE) making most of the operations easier
}
}
}
ifile.close();

编辑2:

我终于成功地使用了 bitset<8> 对象,这对我来说比在 char 中操作位要清楚得多。稍后我可能会用我的工作代码更新我的帖子。我仍然关心效率,您认为使用它比使用 bitset 快得多吗?

最佳答案

如果你不需要在运行时确定你的位数组的大小,你可以使用 std::bitset

http://en.cppreference.com/w/cpp/utility/bitset

关于c++ - 将 8 个 bool 值保存到 1 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21308025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com