1

I have a string say :

string abc = "1023456789ABCD"

I want to convert it into a byte array like :

byte[0] = 0x10;
byte[1] = 0x23;
byte[2] = 0x45; 
----

and so on

I checked some of the posts here but couldn't find the proper solution. Any help will be appreciated. Thanks in Advance.

2

2 Answers 2

3

See it Live on Coliru

#include <string>
#include <cassert>

template <typename Out>
void hex2bin(std::string const& s, Out out) {
    assert(s.length() % 2 == 0);

    std::string extract;
    for (std::string::const_iterator pos = s.begin(); pos<s.end(); pos += 2)
    {
        extract.assign(pos, pos+2);
        *out++ = std::stoi(extract, nullptr, 16);
    }
}

#include <iostream>
#include <vector>

int main()
{
    std::vector<unsigned char> v;

    hex2bin("1023456789ABCD", back_inserter(v));

    for (auto byte : v)
        std::cout << std::hex << (int) byte << "\n";
}

Outputs

10
23
45
67
89
ab
cd
Sign up to request clarification or add additional context in comments.

Comments

-1

when you say 'byte' it looks like you're meaning each character represented in hexidecimal.

in that case you could simply use string.c_str(), as this is just a c-style string (char*).

byte[2] = 0x45

is the same as

byte[2] = 69; //this is 0x45 in decimal

you could assign the output of string.c_str() to another char* if you wanted to store the array seperately.

3 Comments

c_str() doesn't convert anything. It certainly won't turn the example input into the example output.
@interjay: why not? const char* byte = abc.c_str();
@arashkordi Because the question is about converting a hexadecimal string into numbers. Look at the example given, not just at the title.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.