简体   繁体   中英

Reading any file (not .bin file) byte by byte

I want to read any file (.bin, .txt, .jpg, .zip, .mp3 etc.) byte by byte (or bit by bit) and display it on the console (in a format like 00100011). There are some questions answered in the website but it is mostly about .bin files. It should not matter which file format I work with. For example, when you open a .png file in a text editor, you see weird characters on the screen like "∑P®pT™5à*" and I presume these are every 8 bits of the file turned into ASCII letters and displayed on the editor (please correct me if I am wrong).

I am writing this program in c++ and so far I tried

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

to read the file in binary mode and get 8 bits of chunks, but this only works for the .txt files and it just displays the characters in the text file like it would normally do. However does not even work or open other file formats like .png .

Can I get some hints about how can I achieve this, and please correct me if I gave any wrong information.

The issue is that only a portion of values in a byte are printable. For example, the value 0x03 is not printable, but 0x42 is.

I recommend that you cast the variable from uint8_t to unsigned int before printing. Something like cout << hex << (unsigned int)(value) << endl;

Also, don't use char , signed char or unsigned char when reading binary files. Use uint8_t , uint16_t or uint32_t .

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM