0

The problem
I've got some byte buffer, that get's filled during runtime. I want to display the buffer's content, using hex-code. So this is the definition of the buffer:

enum { max_data_length = 8192 }; //8KB
unsigned char stream_data_[max_data_length];

Now I wanted to print the content. The data is stored for example like this:

stream_data_[0] = 124;
stream_data_[1] = 198;
stream_data_[2] = 60;

Now I want to print the contents of this buffer (in hex). I tried several stack overflow posts but they all use unsigned int or fill the arrays. I am really stuck on this problem!

The code
I tried for example:

enum { max_data_length = 3 }; //8KB
unsigned char stream_data_[max_data_length];
stream_data_[0] = 20;
stream_data_[1] = 30;
stream_data_[2] = 40;
char str[16];
sprintf(str, "%X02 ", stream_data_);
std::cout << str;

But I can't understand why the result is always different, each time I run it. For example:

C2CA426002
7C92553002 
Peter
  • 394
  • 7
  • 20

1 Answers1

2

The only issue is that iostream treats unsigned char as a character type, rather than as a small integer. To get around this, just cast your unsigned char to unsigned before outputting it. (For the rest: you'll have to specify hex output, and possibly the width and fill characters, of course.)

To dump an array of unsigned char:

void
dumpArray( unsigned char const* array, int count, std::ostream& dest )
{
    dest.setf( std::ios_base::hex, std::ios_base::basefield );
    dest.fill( '0' );
    while ( count > 0 ) {
        dest << std::setw( 2 ) << static_cast<unsigned>( *array );
        -- count;
        if ( count != 0 ) {
            dest << ' ';
        }
    }
}

(Of course, in production code, you'll want to save the previous formatting, and restore it before returning.)

James Kanze
  • 150,581
  • 18
  • 184
  • 329