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.

sehe
  • 374,641
  • 47
  • 450
  • 633
roheet boss
  • 33
  • 1
  • 6
  • possible duplicate of [Converting a hex string to byte array in c++.](http://stackoverflow.com/questions/17261798/converting-a-hex-string-to-byte-array-in-c) – interjay Oct 15 '13 at 08:48
  • This makes little sense. You probably don't need any conversion. Please explain what your *real* problem is. – n. m. could be an AI Oct 15 '13 at 08:50

2 Answers2

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
sehe
  • 374,641
  • 47
  • 450
  • 633
-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.

CommanderBubble
  • 333
  • 2
  • 9