c++ - Print to stdout, in hex or decimal, a std::string as a sequence of bytes -


this question has answer here:

the api working returns sequence of bytes std::string.

how print stdout, formatted sequence, either in hex or decimal.

this code 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 expecting receive same input, in reverse order. code prints is:

getbytes returned   ☺☻♥♦♣ ♫☼ 

note: sequence of bytes arbitrary sequence of bytes, not representation of written language.

you may want cast chars stored in std::string ints, std::cout wouldn't print them characters, plain integer numbers.
print them in hex use std::hex, showed in 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 per david hammen's comment     return static_cast<unsigned int>(static_cast<unsigned char>(ch)); }  int main() {     string data{"hello"};      cout << hex;     (char ch : data)     {         cout << "0x" << to_uint(ch) << ' ';      } } 

output:

0x48 0x65 0x6c 0x6c 0x6f


Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -