简体   繁体   中英

How to convert std::string with hex values into std::vector<unsigned char>

Hi I have to convert std::string into std::vector<unsigned char> . Let's assume string which contains 14 characters: 020000040800F2 and vector v should contains 7 values. In the real program string will be a little bit longer.

std::vector<unsigned char> v(7);
v[0] = 2; // 02
v[1] = 0; // 00
v[2] = 0; // 00
v[3] = 4; // 04
v[4] = 8; // 08
v[5] = 0; // 00
v[6] = 242; //F2

I am writing in C++17. I was looking for known solutions in algorithm but there are not which could help me. Thank you so much guys for your help.

I can suggest the following straightforward solution shown in the demonstrative program below

#include <iostream>
#include <string>
#include<vector>
#include <cctype>

std::vector<unsigned char> hex_string_to_vector( const std::string &s )
{
    std::vector<unsigned char> v;
    v.reserve( ( s.size() + 1 ) / 2 );

    int second = 1;

    for ( unsigned char c : s )
    {
        c = std::toupper( c );

        if ( std::isxdigit( c ) )
        {
            c = c >= 'A' ? c - 'A' + 10 : c - '0';

            if ( second ^= 1 ) 
            {
                v.back() <<= 4;
                v.back() |= c;
            }
            else
            {
                v.push_back( c );
            }
        }
    }

    return v;
}

int main() 
{
    std::string s( "020000040800F2" );
    std::vector<unsigned char> v = hex_string_to_vector( s );

    for ( const auto &c : v )
    {
        std::cout << static_cast<int>( c ) << ' ';
    }
    std::cout << '\n';

    return 0;
}

The program output is

2 0 0 4 8 0 242 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM