简体   繁体   English

十六进制字符串到无符号字符[]

[英]hex string to unsigned char[]

today I tried to convert a hex string to an unsigned char[] 今天,我尝试将十六进制字符串转换为无符号char []

string test = "fe5f0c";
unsigned char* uchar= (unsigned char *)test.c_str();
cout << uchar << endl;

This resulted in the output of 这导致了输出

fe5f0c

hrmpf :-(. The desired behaviour would be as follows: hrmpf :-(.。所需的行为如下:

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. 打印不可读的ASCII代码。 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. 请注意,我将输入字符串更改为八位数字,因为否则数组将从值0开始,而operator<<会将其解释为结尾,并且您将看不到任何内容。

"fe5f0c" is a string of 6 bytes (7 containing the null terminator). "fe5f0c"是6个字节的字符串(7个包含空终止符)。 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. 如果要在它们之间进行转换,则需要使用类似于@Fred编写的代码来明确地进行转换。

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. 强制转换(在大多数情况下)并不意味着转换,您只是告诉编译器信任您,并且它可以忘记它认为自己对所强制转换的表达式的了解。

这是十六进制字符串文字的一种更简单的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM