Convert an ASCII std::string to hex

前端 未结 2 1661
暖寄归人
暖寄归人 2020-12-20 17:54

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 out

相关标签:
2条回答
  • 2020-12-20 18:11

    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;
    }
    
    0 讨论(0)
  • 2020-12-20 18:13

    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.

    0 讨论(0)
提交回复
热议问题