Search code examples
c++iteratoriostream

std::copy raw data to cout in hex format using ostream_iterator<uint8_t> prints out unformatted data. Why?


The idea is to have a vector containing arbitrary binary data and outputting the bytes it contains to stdout in hexadecimal notation. I use std::copy to copy the bytes from the input vector to stdout. The problem is that the code prints out 0 followed by raw binary data. Here is the code:

auto vec = std::vector<uint8_t> {'h', 'e', 'l', 'l', 'o'};
std::cout << std::hex << std::setfill('0') << std::setw(2);
std::copy(vec.begin(), vec.end(), std::ostream_iterator<uint8_t>(std::cout));

The application prints out "0hello". I would expect it to print out "68656C6C6F". What can be the case?


Solution

  • Simple change, use int instead of uint8_t:

    std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout));
    

    If you want it in uppercase, use std::uppercase.

    operator<< has non-member overloads for char, signed char, and unsigned char. See: uint8_t iostream behavior.