C++ Hex Parsing

前端 未结 4 488
醉话见心
醉话见心 2021-02-05 23:53

I\'m wondering how to convert a hex string to a human readable string (if that makes any sense) this would be my first real encounter with hex values so I\'m still learning abou

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-06 00:12

    The C++-ish way to get a string containing the hexadecimal representation of a given number is to use the hex modifier for streams, as in this example:

    const int i = 0xdeadbeef;
    cout << "0x" << hex << i << endl; // prints "0xdeadbeef"
    

    You can use the same modifier on string streams in case you need to have the hexadecimal representation in a string variable:

    const int i = 0xdeadc0de;
    ostringstream stream;
    stream << "0x" << hex << i;
    
    const string s = stream.str(); // s now contains "0xdeadc0de"
    

    UPDATE:

    If your input data is given as a string containing the hexadecimal representation of the characters of a string, you will need to know the encoding of the input string in order to display it correctly. In the simplest case, the string is something like ASCII which maps one byte to one character. So in a given input "414243", every two characters ("41", "42", "43) map to an ASCII value (65, 66, 67), which map to a character ("A", "B", "C").

    Here's how to that in C++:

    const string hexData = "414243";
    
    assert( hexData.size() % 2 == 0 );
    
    ostringstream asciiStream;
    istringstream hexDataStream( hexData );
    vector buf( 3 ); // two chars for the hex char, one for trailing zero
    while ( hexDataStream.good() ) {
        hexDataStream.get( &buf[0], buf.size() );
        if ( hexDataStream.good() ) {
            asciiStream << static_cast( std::strtol( &buf[0], 0, 16 ) );
        }
    }
    
    const string asciiData = asciiStream.str(); // asciiData == "ABC"
    

    Using std::strtol from makes this easy; if you insist on using a template class for this, use std::stringstream to perform the conversion of the single sub strings (like "41") to decimal values (65).

提交回复
热议问题