Convert an ASCII std::string to hex

14,723

Solution 1

If you don't care about the 0x it's easy to do using std::copy:

#include <algorithm>
#include <sstream>
#include <iostream>
#include <iterator>
#include <iomanip>

namespace {
   const std::string test="hello world";
}

int main() {
   std::ostringstream result;
   result << std::setw(2) << std::setfill('0') << std::hex << std::uppercase;
   std::copy(test.begin(), test.end(), std::ostream_iterator<unsigned int>(result, " "));
   std::cout << test << ":" << result.str() << std::endl;
}

Solution 2

This answer to another question does what you want, I think. You'd have to add a " " as separator argument for the ostream_iterator to get whitespaces between the characters.

Share:
14,723
mspoerr
Author by

mspoerr

Updated on August 01, 2022

Comments

  • mspoerr
    mspoerr over 1 year

    is there an easy way to convert an ASCII std::string to HEX? I don't want to convert it to a number, I only want to convert each ASCII character to it's HEX value. The output format should also be a std::string. i.e.: "TEST" would be "0x54 0x45 0x53 0x54" or some similar format.

    I found this solution, but maybe there is a better one (without string to int to string conversion):

    std::string teststring = "TEST";
    std::stringstream hValStr;
    for (std::size_t i=0; i < teststring.length(); i++)
    {
        int hValInt = (char)teststring[i];
        hValStr << "0x" << std::hex << hValInt << " ";
    }
    

    Thanks,
    /mspoerr

  • Flexo
    Flexo almost 13 years
    I'll post an updated version showing how to add the 0x if you want?
  • Flexo
    Flexo almost 13 years
    +1 for not repeating content! Didn't spot that in my quick search.
  • Björn Pollex
    Björn Pollex almost 13 years
    @awoodland: I simply remembered having answered almost exactly that question before.
  • mspoerr
    mspoerr almost 13 years
    unfortunately this does not work with ASCII chars like 0xFF. I use the string::read() function to read an unsigned char array with ASCII with values > 0x7F. What changes are needed in your solution to get it working in my sceanrio? Thanks again...
  • MSalters
    MSalters almost 13 years
    @mspoerr: There's no ASCII character with value 0xFF. Can't be, since ASCII is a 7 bit character set. That's also why char might or might not be signed; it really doesn't matter to ASCII. char(0x7F) is always positive.
  • mspoerr
    mspoerr almost 13 years
    I mean the 8-Bit version, however it is called (extended ASCII or so).
  • jrwren
    jrwren about 5 years
    This does not keep the setw(2) and setfill('0') beyond the first element of the string.