0

I have a cstring object str = "5043", now i want to convert to Hex and put it in UCHAR array like

UCHAR sample[2];
Sample[0] = 0X50 
Sample[1] = 0X43

How can i do this? please advice me

Andriy
  • 8,486
  • 3
  • 27
  • 51
Naruto
  • 9,476
  • 37
  • 118
  • 201
  • This might have already been answered in this thread: http://stackoverflow.com/questions/3381614/c-convert-string-to-hexadecimal-and-vice-versa – David Z. Apr 20 '12 at 08:13
  • As a possibility for widening the scope of this question, "cstring object str" -> "string". "UCHAR" -> "unsigned char", then just leave this as a C++ question. – Adrian Conlon Apr 20 '12 at 08:46

3 Answers3

1

Have you tried strol? It seems a little low tech, but should do the trick. Don't forget to pass 16 as the base...

You'll need to combine it with a little bit shifting and bitwise anding to split the result into exactly what you require, but that should be straightforward.

Hope this helps,

Adrian Conlon
  • 3,941
  • 1
  • 21
  • 17
  • Actually, i have already got converted value but i just need to update to UCHAR variable – Naruto Apr 20 '12 at 08:30
  • Hmm, in that case, I think you need a different question! i.e. How do I split an integer into two bytes? (For a sixteen bit value) You probably need to right shift 8 bits for the high byte and bitwise and (&) with 255 for the low byte. – Adrian Conlon Apr 20 '12 at 08:36
1

You can scan the hex values directly from the string using sscanf(), something like below:

UCHAR sample[2];
for ( int i = 0; i < str.length() / 2 ; i++) {
    sscanf( (str.substr(i*2,2)).c_str(), "%hx", &sample[i]);
}

h is for short and x is for hexadecimal obviously.

Also, this assumes that the UCHAR array is declared to be half as large as the string size.

vvnraman
  • 1,322
  • 13
  • 21
0

To make your code simpler, you may use an union, e.g.

    union
    {
    UCHAR char_val[2];
    long long_val;
    };

    CString str = "5043";
    long_val = strtol(str.GetString(), nullptr, 16);
    // use char_val here
Andriy
  • 8,486
  • 3
  • 27
  • 51