Search code examples
c++aesunsigned-integerunsigned-char

Converting string to unsigned char


I've spent a while trying to get a string to turn into an array of unsigned chars, but no luck. I'm doing an AES implementation and I have everything set up except the input reading part. This is the code I have ATM.

string text = "E3 FD 51 12" ;
    int size = text.length();

    unsigned char* charText = new unsigned char[size/2];
    int i = 0;
    std::istringstream text_2(text);

    unsigned int c;
    unsigned char ch;
    while (text_2 >> hex >> c)
    {
        ch = c;
        cout <<ch;
    }

I want my string to be in the charText array. The string reads perfectly into the unsigned int, but when I try to place it in the array or in the unsigned char (ch), it gives me gibbrish.

Any help would be great.


Solution

  • Simply output the char as int.

    while (text_2 >> hex >> c)
    {
        ch = c;
        cout << hex << ( int )ch;
    }