0

I'm reading a binary file using C++ and then trying to print the contents. Instead of printing the hex values of the file, however, it prints gibberish character representations of those numbers.

int main(int argc, char** argv)
{
    std::vector<char> bios;
    std::ifstream bios_stream(argv[1], std::ios::binary | std::ios::ate);
    if(bios_stream.good())
    {
        const int bios_size = bios_stream.tellg();
        bios_stream.seekg(0, std::ios_base::beg);
        bios.resize(bios_size);
        bios_stream.read(reinterpret_cast<char*>(bios.data()), bios_size);
        bios_stream.close();
    }
    else {
        std::cout << "Error!\n";
    }

    for(int i = 0; i < bios.size(); i++)
    {
        std::cout << std::hex << std::atoi(bios.at(i));
    }

    return 0;
}

Any idea how to make this print out the hex representation of the file (i.e. A0FFB126C3 etc)?

  • `atoi` converts a string to an integer. `bios.at(i)` is a character, not a string. Your compiler should have warned you. Use: `(int)bios.at( i )` – zdf May 18 '20 at 19:44
  • @zdf that's great, but for some reason some of the bytes print fine (i.e. FA), and some of them print with 6 F's before them. Here's a sample: '0b 70 60 47 fffffff4 46 ffffffff fffffff7 ffffff82 ffffffff 40' – Marina Terry May 18 '20 at 20:27
  • See the link at the top of your post. – zdf May 18 '20 at 20:34
  • @zdf That doesn't answer my question. I'm already casting to an unsigned int so it prints as a number instead of an ASCII character, but I'm getting an FFFFFF prefix on most of the numbers. – Marina Terry May 18 '20 at 20:40
  • What you see are negative numbers. You must use an `unsigned char` buffer instead of a `char` one. You must also format the numbers as in the above link. – zdf May 18 '20 at 20:45
  • 1
    @zdf Ahhh negative numbers, I didn't even think of that! Thanks! – Marina Terry May 18 '20 at 20:52

0 Answers0