gpt4 book ai didi

c++ - 二进制输出 C++

转载 作者:太空宇宙 更新时间:2023-11-04 11:27:13 24 4
gpt4 key购买 nike

我正在为一个类开发一个 C++ 文本文件压缩程序。除了能够以二进制模式输出到文件外,我一切正常。我正在使用:

FILE* pFile;
pFile = fopen(c, "wb");

为了以二进制方式打开文件进行写入,

bool Buffer[8] = { 0, 0, 0,0, 0,0, 0,0 };

我使用 bool 缓冲区(初始化为全 0)来存储 1 和 0 来存储数据的每个字节,直到我使用 fwrite。

vector<bool> temp2 = bitstring[temp];//bitstring refers to a vector in a map at key [temp]
for (vector<bool>::iterator v = temp2.begin(); v != temp2.end(); ++v)
{

if (j < 8)//To create an 8 bit/byte buffer
{
if (*v == 1)//Checks the vector at that position to know what the bit is.
Buffer[j] =1;//sets the array at 'j' to 1
else
Buffer[j] =0 ;//sets the array at 'j' to 0

j++;
}
else //once the Buffer hits 8 it will print the buffer to the file
{

fwrite(Buffer,1,sizeof(Buffer), pFile);

clearBuffer(Buffer);//Clears the buffer to restart the process.
j = 0;

}

}

( vector 迭代器)正在遍历分配给特定字符的 bool vector ,本质上是表示该字符的唯一二进制字符串。我的问题是,它不是在缓冲区中以二进制形式输出,而是以二进制模式输出本质上是 ASCII 字符,而不仅仅是数字作为二进制。这最终使文件比需要的大得多。我怎样才能将缓冲区更改为仅输出位。有人告诉我使用按位运算符,但我找不到太多关于在 C++ 中实现它的文档。感谢您的帮助,

最佳答案

我会使用 std::bitset首先,为此目的绝对灵活

std::bitset<8> BufferBits;
vector<bool> temp2 = bitstring[temp];//bitstring refers to a vector in a map at key [temp]
for (vector<bool>::iterator v = temp2.begin(); v != temp2.end(); ++v)
{

if (j < 8)//To create an 8 bit/byte buffer
{
if (*v == 1)//Checks the vector at that position to know what the bit is.
BufferBits[j] =1;//sets the array at 'j' to 1
else
BufferBits[j] =0 ;//sets the array at 'j' to 0

j++;
}
else //once the Buffer hits 8 it will print the buffer to the file
{
unsigned long i = BufferBits.to_ulong();
unsigned char c = static_cast<unsigned char>( i );
fwrite(&c, sizeof(char), 1, pFile);

BufferBits.reset();//Clears the buffer to restart the process.
j = 0;

}

}

注意:我刚刚考虑了关于你的位 vector 的问题

关于c++ - 二进制输出 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26223666/

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