二进制输出c ++

时间:2014-10-06 19:43:42

标签: c++ binary bit-manipulation fwrite

我正在为一个类开发一个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;

            }

        }

(向量迭代器)正在通过分配给特定字符的bool向量,本质上是表示字符的唯一二进制字符串。我的问题是,它不是在缓冲区中输出二进制文件,而是以二进制模式输出基本上是ASCII字符,而不仅仅是二进制数字。最终使文件WAY大于它需要的大小。我怎么能将缓冲区更改为输出位。有人告诉我使用按位运算符,但我找不到很多关于在c ++中实现它的文档。任何帮助表示赞赏,

3 个答案:

答案 0 :(得分:1)

我首先会使用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;

            }

        }

注意:我刚刚考虑了有关您的位向量的问题

答案 1 :(得分:0)

要在一个字节中设置一个位,请使用shift和一个或。当j为0时,此代码以字节中的最高位开始,这是通常的惯例。

char data = 0;
// ...
data |= 0x80 >> j;

答案 2 :(得分:0)

要设置字节中的各个位,可以使用并集和位域:

typedef union 
{
  struct
  {
    unsigned char value;
  } byte;
  struct
  {
    unsigned char b0:1;
    unsigned char b1:1;
    unsigned char b2:1;
    unsigned char b3:1;
    unsigned char b4:1;
    unsigned char b5:1;
    unsigned char b6:1;
    unsigned char b7:1;
  } bits;
} u; 

int main()
{
  u buffer = {{0}};

  buffer.bits.b0 = 1;
  buffer.bits.b1 = 0;
  buffer.bits.b2 = 1;

  cout << static_cast<int>(buffer.byte.value) << endl;
  return 0;
}

将打印5(取决于您的PC的字节顺序)

相关问题