char形输入 怎么转 二进制型输出?

来源:百度知道 编辑:UC知道 时间:2024/06/08 12:49:37
void main(void)
{
ifstream infile("lena.dat",ios::in|ios::binary|ios::nocreate);
ofstream outfile("f2.dat",ios::binary|ios::out);

infile.unsetf(ios::skipws);
char ch;
//long int a;
ofstream &put(char &ch);
while(infile>>ch)
{
//infile>>ch;
//ch=a;
//a=ch;
outfile<<ch;

}
infile.close();
outfile.close();
}

执行后F2没有以二进制输出 郁闷~~~

文件的打开方式加入binary并不代表以二进制数的形式读入或者写出,而只是用于保护一些文件中不能被识别的其他符号,否则它们不会被读入或写出,你想用读一般文件然后用二进制写出要自己写函数:

#include <iostream>
#include <fstream>
#include <streambuf>
using namespace std;

void binary_print(char c)
{
for(int i = 0; i < 8; ++i)
{
if(c << i & 0x80)
cout << '1';
else
cout << '0';
}
cout << ' ';
}

int main()
{
ifstream inf("in.txt");
ofstream ouf("out.txt");

inf.unsetf(ios::skipws);
streambuf* strm_buffer = cout.rdbuf(ouf.rdbuf());

char c;
while(inf.get(c))
{
binary_print(c);
}
cout.rdbuf(strm_buffer);
}

in.txt的内容为:

No one objects if you are doing a good programming job for someone who you respect.

转化为二进制输出:

01001110 01101111 00100000 01101111 01101110 01100101