c++ - Print to stdout, in hex or decimal, a std::string as a sequence of bytes -
this question has answer here:
- uint8_t can't printed cout 8 answers
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 char
s stored in std::string
int
s, 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
Post a Comment