How to convert Byte Array to Hexadecimal String in C++?

前端 未结 4 2065
别跟我提以往
别跟我提以往 2020-12-17 22:29

I am looking for a fastest way to convert a byte array of arbitrary length to a hexadecimal string. This question has been fully answered here at StackOverflow for C#. Some

4条回答
  •  萌比男神i
    2020-12-17 22:38

    You can use the C++ Standard Library and or you can use boost::lexical_cast

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    // use this macro for c++11 feature
    #define USE_CPP11
    
    int main(int argc, char* argv[])
    {
        array hexArr = {0x01, 0xff, 0x55};
        const char separator = ' ';             // separator between two numbers
        ostringstream os;
        os << hex << setfill('0');  // set the stream to hex with 0 fill
    
    #ifdef USE_CPP11
        std::for_each(std::begin(hexArr), std::end(hexArr), [&os, &separator] (int i)
        {
            os << setw(2) << i << separator;
        });
    #else       // c++03
        typedef array::const_iterator const_iterator;
        for (const_iterator it = hexArr.begin(); it != hexArr.end(); ++it)
        {
            os << setw(2) << int(*it) << separator;
        }
    #endif
        os << dec << setfill(' ');          // reset the stream to "original"
    
        // print the string
        cout << "the string array is: " << os.str() << endl;
    
        return EXIT_SUCCESS;
    }
    

提交回复
热议问题