1

The API I am working with returns a sequence of bytes as a std::string.

How do I print this to stdout, formatted as a sequence, either in hex or decimal.

This is the code I am using:

        int8_t i8Array[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
        std::string i8InList(reinterpret_cast<const char*>(i8Array), 16);
        std::string i8ReturnList;

        client.GetBytes(i8ReturnList, i8InList);

        cout << "GetBytes returned ";
        std::copy(i8ReturnList.begin(), i8ReturnList.end(),   std::ostream_iterator<int8_t>(std::cout << " " ));

I am expecting to receive the same input, but in reverse order. What this code prints however is:

GetBytes returned   ☺☻♥♦♣
♫☼

NOTE: The sequence of bytes is an arbitrary sequence of bytes, it is not a representation of written language.

Mr.C64
  • 41,637
  • 14
  • 86
  • 162
Rire1979
  • 652
  • 12
  • 24
  • 1
    Comments removed. Please keep them civil and related to request clarification etc... regarding the question. Thank you. – Jon Clements Jun 29 '15 at 18:39

2 Answers2

4

You may want to cast the chars stored in the std::string to ints, so std::cout wouldn't print them as characters, but just as plain integer numbers.
To print them in hex use std::hex, like showed in the following compilable code snippet (live on Ideone):

#include <iostream>
#include <string>
using namespace std;

inline unsigned int to_uint(char ch)
{
    // EDIT: multi-cast fix as per David Hammen's comment
    return static_cast<unsigned int>(static_cast<unsigned char>(ch));
}

int main()
{
    string data{"Hello"};

    cout << hex;
    for (char ch : data)
    {
        cout << "0x" << to_uint(ch) << ' '; 
    }
}

Output:

0x48 0x65 0x6c 0x6c 0x6f

Mr.C64
  • 41,637
  • 14
  • 86
  • 162
  • You'll get `0xffffffXX` if one of those bytes has it's high order bit set and you happen to be on a computer that uses signed chars. Using `static_cast(static_cast(ch))` would work better here. – David Hammen Jun 29 '15 at 18:29
  • @DavidHammen: Thanks. I've updated my code snippet following your multi-cast suggestion. – Mr.C64 Jun 29 '15 at 18:36
3

The stream will interpret those bytes as characters, and when the console gets those characters it will display whatever the encoding says it should display.

Use e.g. int as std::ostream_iterator template parameter instead to print them as numbers.

Hcorg
  • 11,598
  • 3
  • 31
  • 36
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621