Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from char string to an array of uint8_t?

Tags:

c++

I'm reading a string from a file so it's in the form of a char array. I need to tokenize the string and save each char array token as a uint8_t hex value in an array.

char* starting = "001122AABBCC";
// ...
uint8_t[] ending = {0x00,0x11,0x22,0xAA,0xBB,0xCC}

How can I convert from starting to ending? Thanks.

like image 863
Nirav Trivedi Avatar asked Jul 26 '12 20:07

Nirav Trivedi


1 Answers

Here is a complete working program. It is based on Rob I's solution, but fixes several problems has been tested to work.

#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <iostream>


const char* starting = "001122AABBCC";
int main() 
{
    std::string starting_str = starting;
    std::vector<unsigned char> ending;
    ending.reserve( starting_str.size());
    for (int i = 0 ; i < starting_str.length() ; i+=2) {
        std::string pair = starting_str.substr( i, 2 );
        ending.push_back(::strtol( pair.c_str(), 0, 16 ));
    }

    for(int i=0; i<ending.size(); ++i) {
        printf("0x%X\n", ending[i]);
    }

}
like image 88
OfNothing Avatar answered Oct 15 '22 10:10

OfNothing