bin2txt.cpp

来自「两条5级的并行流水线」· C++ 代码 · 共 74 行

CPP
74
字号
#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

void bin2str(char ch, char *str);

void main(int argc, char**argv)
{
	int lineNum;

	char str[9];
	char srcFilename[1024],dstFilename[1024];

	if(argc<3)
	{
		cout << "Bin2Txt [sourcefile] [destinedfile]" << endl;
		return;
	}

	strcpy(srcFilename,argv[1]);
	strcpy(dstFilename,argv[2]);

	ifstream in;
	ofstream out;

	in.open(srcFilename,ios::binary);
	if(!in.is_open())
	{
		cout << "Source file cannot be opened" << endl;
		return;
	}

	out.open(dstFilename);
	if(!out.is_open())
	{
		cout << "Destined file cannot be written" << endl;
		return;
	}

	char ch;

	lineNum = 0;

	while(true)
	{
		in.read((char *)&ch, 1);
		if(in.eof()) break;

		++lineNum;

		bin2str(ch, str);
		out << str << endl;
		if(!(lineNum%4))
			out<<endl;
	}

	in.close();
	out.close();
	
	return;
}

void bin2str(char ch, char *str)
{
	int i;
	for(i=0; i<8; ++i)
	{
		str[i] = '0' + ((unsigned char)ch >> (7-i) & 0x1);
	}
	str[8] = 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?