0

I intend to convert a string into an array of numbers. For instance the below code works well:

// A program to demonstrate the use of stringstream 
#include <iostream> 
#include <sstream> 
using namespace std; 

int main() 
{ 
    string s = "12345"; 

    // object from the class stringstream 
    stringstream geek(s); 

    // The object has the value 12345 and stream 
    // it to the integer x 
    int x = 0; 
    geek >> x; 

    // Now the variable x holds the value 12345 
    cout << "Value of x : " << x; 

    return 0; 
}

How do I do it for a very big string. For example, string s = "77980989656B0F59468581875D719A5C5D66D0A9AB0DFDDF647414FD5F33DBCBE"

I need to store this into an array of chars, arr[32]. arr[0] should have 0x77, arr[1] should have 0x98 and so on. Considering string s is of 64 bytes. my array would be 32 bytes long.

Can someone help with this?

1 Answers1

0

You can try to split the input string into substrings where each substring has 2 characters length. Then convert the hexadecimal substring using std::stoi() function into integer and store each converted result to an std::vector container:

#include <vector>
#include <iostream>


std::vector<int> convert(const std::string& hex_str) {

    std::vector<int> output;
    std::string::const_iterator last = hex_str.end();
    std::string::const_iterator itr = hex_str.cbegin();

    if (hex_str.size() % 2) {
        last--;
    }

    while(itr != last) {

        std::string sub_hex_str;
        std::copy(itr,itr+2,std::back_inserter(sub_hex_str));
        try {
            output.push_back(std::stoi(sub_hex_str,0,16));
        }catch(const std::exception& e) {
            std::cerr << sub_hex_str << " : " << e.what() << std::endl;
        }

        itr += 2;       
    }

    return output;
}

int main()
{
    std::string a = "77980989656B0F59468581875D719A5C5D66D0A9AB0DFDDF647414FD5F33DBCBE";

    const auto output = convert(a);

    for(const auto& a: output) {
        std::cout << a << std::endl;
    }
}