Convert from String to Unsigned Char Array in C ++

0

I need to convert a string of string characters to an unsigned char array in this way:

string str_texto = "Hola Mundo!";
unsigned char uchar_texto[80];

Exit:

uchar_texto[0] = 0x68 //H
uchar_texto[1] = 0x6F //o

So far I have done this and it works well once, the problem is that if I use it again, the second time it stops working (I do not know why but it does not copy anything to the unsigned char even renaming all the variables):

char *c_key1 = new char(16 + 1);

for(unsigned i = 0, unsigned_char_val; i < str_texto.length(); i += 2)
{
    sscanf(str_texto .c_str() + i, "%2X", &unsigned_char_val);
    c_key1[i/2] = unsigned_char_val;
    uchar_texto[i/2] = c_key1[i/2];
}

I also know that this is another way of doing it, but if I had a 500-character string, the code would be huge:

sscanf(str_texto.c_str(), "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX...",
        &uchar_texto[0], &uchar_texto[1], &uchar_texto[2]...);

That's why I'm looking for a way other than these two to make that conversion.

    
asked by Noe Cano 25.08.2018 в 00:30
source

2 answers

1

It's all much simpler than what you're doing. But before explaining my proposal we will correct your errors and failures.

To start you have marked the question as

answered by 25.08.2018 / 15:25
source
0
unsigned char m_Test[20];

strcpy( static_cast <char*>( m_Test ), "Hello World" );

Use this example obviously if you want you can change Hello World with your variable string . Make sure char is the right size or enough to store the string so I recommend changing unsigned char m_Test[20]; instead of 20 putting what you need.

    
answered by 25.08.2018 в 00:46