roheet boss
roheet boss

Reputation: 33

converting a string array to byte array in c++

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.

Upvotes: 1

Views: 1115

Answers (2)

CommanderBubble
CommanderBubble

Reputation: 333

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.

Upvotes: -1

sehe
sehe

Reputation: 392833

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

Upvotes: 3

Related Questions