逐字节

时间:2016-02-03 01:57:02

标签: c++ byte ascii readfile

我希望逐字节(或逐位)读取任何文件(.bin,.txt,.jpg,.zip,.mp3等)并将其显示在控制台上(以00100011)的格式。网站上有一些问题,但主要是关于.bin文件。我使用哪种文件格式无关紧要。例如,当您在文本编辑器中打开.png文件时,您会在屏幕上看到奇怪的字符,如“ΣP®pT™5à*”,我认为这些文件的每8位都变为ASCII字母并显示在编辑(如果我错了,请纠正我。)

我用c ++编写这个程序,到目前为止我试过

fstream file("foo.txt", ios_base::binary);

以二进制模式读取文件并获取8位块,但这仅适用于.txt文件,它只是像通常那样在文本文件中显示字符。但是甚至无法正常工作或打开其他文件格式,例如.png

我能否获得一些关于如何实现这一目标的提示,如果我提供了错误的信息,请纠正我。

2 个答案:

答案 0 :(得分:2)

问题是字节中只有一部分值是可打印的。例如,值0x03不可打印,但0x42是。

我建议您在打印之前将变量从uint8_t转换为unsigned int。像cout << hex << (unsigned int)(value) << endl;

这样的东西

此外,在阅读二进制文件时,请勿使用charsigned charunsigned char。使用uint8_tuint16_tuint32_t

答案 1 :(得分:0)

You are probably assigning the values to a "char" datatype. You should always use unsigned types ("unsigned char" should suffice for your case) because there are no negative values for binary files and you will be able to read 0-255 instead of just 0-127(text characters). Then, if you want it displayed in binary, you can use this:

unsigned char c = 251;
char binary[8];
itoa(c, binary, 2);
cout << binary << endl;