使用C ++将无符号字符作为二进制文件存储在文件中?

时间:2016-09-13 16:00:21

标签: c++ file binary printf bits

我已编写以下代码将Pin和Pout中的数据打印到文件中:

void run() {
while ( in.readable() >= 17*11*12+SIZE_RSPACKET &&
    out.writable() >= 1 ) {
  u8 *pin = in.rd()+17*11*12, *pend=pin+SIZE_RSPACKET;
  u8 *pout= out.wr()->data;
  for ( int delay=17*11; pin<pend;
    ++pin,++pout,delay=(delay-17+17*12)%(17*12) )
*pout = pin[-delay*12];
  in.read(SIZE_RSPACKET);
  out.written(1);

 /* Printing output after Deinterleaving to file: Need to Turn this into Binary */   

FILE * F; // Create File
F = fopen("Deinterleaving.txt", "wb"); // Open Deinterleaving File 

for(int i = 0; i < SIZE_RSPACKET; i++){ // For Every Packet (204 bytes)
    // Print char for data coming and going out (Not Binary) to file
    fprintf(F, "%s %u %s %u \n", " Data coming in: ", pin[i], " Data Going Out: ", pout[i]); 

   } 
    fflush(F);
    fclose(F);
  }
}

这给了我输出:

 Data coming in:  71            Data Going Out:  0 
 Data coming in:  99            Data Going Out:  0 
 Data coming in:  46            Data Going Out:  0 
 Data coming in:  84            Data Going Out:  0 
 Data coming in:  129           Data Going Out:  0 
 Data coming in:  134           Data Going Out:  0 
 Data coming in:  1             Data Going Out:  0 
 Data coming in:  101           Data Going Out:  0 
 Data coming in:  15            Data Going Out:  1

如何将每个8个数据包转换为二进制副本,以便输出如下所示?

输出应该是什么样的(即1个块(8个包,每个包含204个字节)):

71 99 46 84 129 134 1 101 -> 01000111 01100011 0101110 01010100 010000001 010000110 00000001 01100101 

1 个答案:

答案 0 :(得分:0)

使用fwrite将数据的内部表示写入文件:

fwrite(&pin[0], 1, sizeof(pin), F);

此外,以二进制模式打开文件以避免翻译,例如值0x0d0x0d, 0x0a替换。

fprintf用于将内部表示转换为人类可读的形式。