-1

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.

inzombiak
  • 171
  • 2
  • 14
  • 2
    The first two characters are outside the ASCII range, the 51 yields a `'Q'` and the last character is a form feed. You might call this gibberish but what did you expect...? – Dietmar Kühl Nov 28 '13 at 23:25
  • Not that? What do I need to do read it correctly? – inzombiak Nov 28 '13 at 23:29
  • Well, what is _correct_ if you don't like to convert these values to their character values? If you print the `char` values as `int` using `std::cout << std::hex << int(ch);` you'll get the original values back (obviously, if your values are smaller than 16 you'll need to a set up a width and a `'0'` fill character). – Dietmar Kühl Nov 28 '13 at 23:36
  • 1
    So I'm reading it right just outputting it wrong? – inzombiak Nov 28 '13 at 23:46

1 Answers1

0

Simply output the char as int.

while (text_2 >> hex >> c)
{
    ch = c;
    cout << hex << ( int )ch;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335