How do I print bytes as hexadecimal? How do I print bytes as hexadecimal? arrays arrays

How do I print bytes as hexadecimal?


If you want to use C++ streams rather than C functions, you can do the following:

int ar[] = { 20, 30, 40, 50, 60, 70, 80, 90 };const int siz_ar = sizeof(ar) / sizeof(int);for (int i = 0; i < siz_ar; ++i)    cout << ar[i] << " ";cout << endl;for (int i = 0; i < siz_ar; ++i)    cout << hex << setfill('0') << setw(2) << ar[i] << " ";cout << endl;

Very simple.

Output:

20 30 40 50 60 70 80 9014 1e 28 32 3c 46 50 5a 


Well you can convert one byte (unsigned char) at a time into a array like so

char buffer [17];buffer[16] = 0;for(j = 0; j < 8; j++)    sprintf(&buffer[2*j], "%02X", data[j]);


C:

static void print_buf(const char *title, const unsigned char *buf, size_t buf_len){    size_t i = 0;    fprintf(stdout, "%s\n", title);    for(i = 0; i < buf_len; ++i)    fprintf(stdout, "%02X%s", buf[i],             ( i + 1 ) % 16 == 0 ? "\r\n" : " " );}

C++:

void print_bytes(std::ostream& out, const char *title, const unsigned char *data, size_t dataLen, bool format = true) {    out << title << std::endl;    out << std::setfill('0');    for(size_t i = 0; i < dataLen; ++i) {        out << std::hex << std::setw(2) << (int)data[i];        if (format) {            out << (((i + 1) % 16 == 0) ? "\n" : " ");        }    }    out << std::endl;}