本文介绍了十六进制字符串到无符号字符[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
今天我尝试将十六进制字符串转换为无符号字符[]
today I tried to convert a hex string to an unsigned char[]
string test = "fe5f0c";
unsigned char* uchar= (unsigned char *)test.c_str();
cout << uchar << endl;
这导致了
fe5f0c
hrmpf :-(.所需的行为如下:
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;
打印不可读的 ascii 代码.我经常做错事^^.将不胜感激任何建议.
which prints unreadable ascii code. As so often I am doing something wrong ^^. Would appreciate any suggestions.
提前致谢
推荐答案
当然,您只需在解析后隔离您感兴趣的位:
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;
}
请注意,我将输入字符串更改为八位数字,否则数组将以值 0 开头,并且 operator<<
会将其解释为结尾,而您不会能够看到任何东西.
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.
这篇关于十六进制字符串到无符号字符[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!