簡體   English   中英

使用 C++ 將無符號字符作為二進制存儲在文件中?

[英]Storing Unsigned Char as Binary in File with C++?

我編寫了以下代碼將 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 

使用fwrite將數據的內部表示寫入文件:

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

此外,以二進制模式打開文件以避免轉換,例如將值0x0d替換為0x0d, 0x0a

fprintf用於將內部表示轉換為人類可讀的形式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM