0

I want to convert a std::string to hexadecimal in C++ using std::hex manipulator but i can't get it working right.

This is what i wrote so far:

#include <iostream>
#include <sstream>

int main() {
    std::string a = "hello world";
    std::stringstream ss;

    for(size_t i = 0; i < a.length(); i++) { // Print one character at the time
        ss << std::hex << (int)a[i]; 
        std::cout << ss.str() << " ";
        ss.str(std::string());
    }

    return 0;
}

The output of the same string using hexdump is 6568 6c6c 206f 6f77 6c72 0a64 while the previous code prints something like: 6865 6c6c 6f20 776f 726c 64, so i'm suspecting this is something related with endianess of the platform. My question is: how can i convert a string without messing with endianess?

beep
  • 1,057
  • 2
  • 11
  • 23
  • FYI, you don't need the `std::stringstream`, you can use `std::hex` with `std::cout` directly: `for(size_t i = 0; i < a.length(); i++) { std::cout << std::hex << (int)a[i] << " "; }` – Remy Lebeau Feb 09 '20 at 18:22
  • 1
    Either way, `std::string` contains 1-byte `char` elements. The code you have shown prints a space after EVERY byte, but the two outputs you have shown are lacking spaces between every 2nd byte. The code shown cannot possibly create that output, it MUST output this instead : `68 65 6c 6c 6f 20 77 6f 72 6c 64` ([live demo](https://ideone.com/adGOdg)). There is no endian issue in the code shown, so clearly this is not the real code you are actually having trouble with – Remy Lebeau Feb 09 '20 at 18:28
  • The endinanness issue is in whatever you used that generates your hexdump. Pay attention that it's dumping 16 bit values. – Sam Varshavchik Feb 09 '20 at 18:30
  • @MdGolamRahmanTushar in that answer they reinvent the wheel...if possible i would like to use something from the STL. Also, the use C like strings instead of std::string(as i pointed in my question). – beep Feb 09 '20 at 19:11
  • @RemyLebeau That's not the point. The problem is how to deal with endianess, not with spaces. – beep Feb 09 '20 at 19:14
  • @RemyLebeau btw why hexdump prints the same string in different order? who of them is right? – beep Feb 09 '20 at 19:16
  • Maybe i found [something](https://unix.stackexchange.com/a/55772/294492): _"The traditional BSD hexdump utility uses the platform's endianness, so the output you see means your machine is little-endian."_ So i think that my code was just fine. – beep Feb 09 '20 at 19:28
  • @icebit `'h'` is 0x68, `'e'` is 0x65, `'l'` is 0x6C, etc. The code you showed can output that only as `68 65 6c 6c ...`, not as `6865 6c6c ...`, and certainly not as `6568 6c6c ...`. Any hex editor that prints out 8bit values using 16bit endian-sensitive values is not doing you any good. – Remy Lebeau Feb 09 '20 at 22:29

0 Answers0