开发者

hex string to unsigned char[]

today I tried to convert a hex string to an unsigned char[]

string test = "fe5f0c";
unsigned char* uchar= (unsigned char *)test.c_str();
cout << ucha开发者_如何学Pythonr << endl;

This resulted in the output of

fe5f0c

hrmpf :-(. The desired behaviour would be as follows:

unsigned char caTest[2]; 
caTest[0] = (unsigned char)0xfe;
caTest[1] = (unsigned char)0x5f;
caTest[2] = (unsigned char)0x0c;
cout << caTest << endl;

which prints unreadable ascii code. As so often I am doing something wrong ^^. Would appreciate any suggestions.

Thanks in advance


Sure, you just have to isolate the bits you are interested in after parsing:

#include <string>
#include <cstdlib>
#include <iostream>

typedef unsigned char byte;

int main()
{
    std::string test = "40414243";
    unsigned long x = strtoul(test.c_str(), 0, 16);
    byte a[] = {byte(x >> 24), byte(x >> 16), byte(x >> 8), byte(x), 0};
    std::cout << a << std::endl;
}

Note that I changed the input string to an eight digit number, since otherwise the array would start with the value 0, and operator<< would interpret that as the end and you wouldn't be able to see anything.


"fe5f0c" is a string of 6 bytes (7 containing the null terminator). If you looked at it as an array you would see:

char str[] = { 102, 101, 53, 102, 48, 99 };

But you want

unsigned char str[] = { 0xfe, 0x5f, 0x0c };

The former is a "human readable" representation whereas the latter is "machine readable" numbers. If you want to convert between them, you need to do so explicitly using code similar to what @Fred wrote.

Casting (most of the time) does not imply a conversion, you just tell the compiler to trust you and that it can forget what it thinks it knows about the expression you're casting.


Here is a simpler way for hexadecimal string literals:

unsigned char *uchar = "\xfe\x5f\x0c";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜