1. 程式人生 > >二進位制檔案轉文字檔案的實現

二進位制檔案轉文字檔案的實現

 /*
說明:程式只能處理不帶回車/換行的二進位制檔案。

[bina.txt]內容如下:
----------------------------------------------------------------------
010010010010000001100101011011100110101001101111011110010110010101100100001000000110001101101111011001000110100101101110011001110010000001110100011010000110100101110011001000000111010001101111011011110110110000101100001000000100100100100000011010000110111101110000011001010010000001111001011011110111010100100000011000010111001001100101001000000110010101101110011010100110111101111001011010010110111001100111001000000111010001101000011010010111001100100000011000100111100100100000011101010111001101101001011011100110011100100000011010010111010000101110000011010000101001001100011010010111011001100101010100000110100001111001011100110110100101100011011100110010111001000011011011110110110100001101000010100100010001100101011101100110010101101100011011110111000001100101011100100010000001010100011001010110000101101101
----------------------------------------------------------------------

轉換出來的[text.txt]內容如下:
----------------------------------------------------------------------
I enjoyed coding this tool, I hope you are enjoying this by using it.

LivePhysics.Com
 
Developer Teamm
----------------------------------------------------------------------

*/

#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <string>

using namespace std;
#define NSIZE  8                            // 每次讀取字元數目為8(正好是一個字元)

void main()
{
 ifstream ifile;
 ofstream ofile; 

 int i = 0, j = 0, iTemp = 0;

 int ibina[NSIZE];       // 存放二進位制位元組流
 char cRead[NSIZE];              // 儲存讀檔案流的資料
 char cChar;                  // 存放由二進位制還原的字元

 ifile.open("bina.txt", ios::in | ios::binary);
 ofile.open("text.txt");

 if (!ifile)
 {
  cout << "cannot open file/n";
  return;
 }

    while(!ifile.eof())
    {
  ifile.read(cRead, NSIZE);

  // 將字元轉換為0101形式後存入整型陣列
  for(i = 0; i < NSIZE; i++)
  {
   ibina[i] = (cRead[i] - '0');    // 減'0'才能儲存為0101形式,否則會儲存為ASCII碼形式
  }

  // 每8位為一個位元組進行還原
  iTemp = 1;
  cChar = 0;
  for(j = 7; j >= 0; j--)
  {
   cChar += ibina[j] * iTemp;
   iTemp *= 2;
  }

  cout << cChar;

  ofile.write(&cChar, 1);
    }

 ifile.close();
 ofile.close();
}

--------------------------------------------------------------------------------------------------------

P.S.目前部落格無法回覆:(只好在這裡回覆。

回覆 lovemysea:

ifile.read(cRead, NSIZE);所在的迴圈執行完後,cRead字元型陣列的每一個元素(1個位元組)的值是:0x30(即:0)或0x31(即:1)。
一個位元組(8位)可對應成一個ASCII碼,字元“0”的ASCII是“0x30”。
ibina整形陣列的每一個元素(4個位元組,32位),在後面“每8位為一個位元組進行還原”轉換時我們只使用ibina陣列元素的最低位(儲存的是:1或0)。
ibina[i] = (cRead[i] - '0'); 等價於ibina[i] = (cRead[i] - 0x30); 目的就是為了將從二進位制檔案讀取到得8個二進位制數分別儲存到ibina陣列的8個元素中。
這段程式碼,也是從網上整理而來,之前我也是不求甚解:-)正好一起學習了!