Search code examples
c++binaryfiles

Displaying Hex codes from buffer after reading from a file


I'm trying to store the hex codes read from a file into a buffer and then display it on the console, so far it doesn't seem to work. This is my code:

using namespace std;

int main()
{
 ifstream file("Fishie.ch8",ios::binary);
 if (!file.is_open())
{
    cout << "Error";
}
else
{
    file.seekg(0, ios::end);
    streamoff size = file.tellg();
    file.seekg(0, ios::beg);
    char *buffer = new char[size];
    file.read(buffer, size);
    file.close();
    for (int i = 0; i < size; i++)
    {
        cout <<hex<< buffer[i] << " ";
    }
}
delete[] buffer;
cin.get();
}

The expected output should be this:

00 e0 a2 20 62 08 60 f8 70 08 61 10 40 20 12 0e
d1 08 f2 1e 71 08 41 30 12 08 12 10 00 00 00 00
00 00 00 00 00 18 3c 3c 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
3e 3f 3f 3b 39 38 38 38 00 00 80 c1 e7 ff 7e 3c
00 1f ff f9 c0 80 03 03 00 80 e0 f0 78 38 1c 1c
38 38 39 3b 3f 3f 3e 3c 78 fc fe cf 87 03 01 00
00 00 00 00 80 e3 ff 7f 1c 38 38 70 f0 e0 c0 00
3c 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

Instead the above output I get some strange looking symbols with lots of empty spaces. It looks like this: binary file output What could be the problem?


Solution

  • As you buffer is char all elements will be printed as characters. What you want is the number converted to hex.

    BTW: As you want a conversion to hexadecimal output, it is a question if you really want to read char from file or unsigned char.

    As you find out, the signature for istream.read uses char you have to convert before to unsigned char and than to unsigned int like:

    cout <<hex<< (unsigned int)(unsigned char) buffer[i] << " ";
    

    For real c++ users you should write a fine static_cast ;)

    This will print out the hex values. But if you have a CR you will see a 'a' instead of '0a', so you have to set your width and fill char before:

    cout.width(2);
    cout.fill('0');
    
    for (int i = 0; i < size; i++)
    {   
        cout <<hex<< (unsigned int)(unsigned char)buffer[i] << " ";
    }   
    

    BTW: delete[] buffer; is in wrong scope and must be shifted in the scope where it was defined.