如何将一组十六进制字符串转换为字节阵列
how to convert a set of hex strings to byte array
我有一个char *str = "13 00 0A 1B CA 00";
我需要输出为BYTE bytes[] = { 0x13, 0x00, 0x0A, 0x1B, 0xCA, 0x00 };
有人可以帮助解决方案吗?
您将需要解析两个字符中的每个字符,然后将它们转换为BYTE
。这并不难。
std::stringstream converter;
std::istringstream ss( "13 00 0A 1B CA 00" );
std::vector<BYTE> bytes;
std::string word;
while( ss >> word )
{
BYTE temp;
converter << std::hex << word;
converter >> temp;
bytes.push_back( temp );
}
此答案假设输入格式实际上是每个十六进制字节的3个字符。我为简单起见使用sscanf
,streams
显然也是一个选择。
std::vector<BYTE> bytes;
char *str = "13 00 0A 1B CA 00";
std::string input(str);
size_t count = input.size()/3;
for (size_t i=0; i < count; i++)
{
std::string numStr = input.substr(i*3, input.find(" "));
int num=0;
sscanf(numStr.c_str(), "%x", &num);
bytes.push_back((BYTE)num);
}
// You can access the output as a contiguous array at &bytes[0]
// or just add the bytes into a pre-allocated buffer you don't want vector
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 指向存储在字符串 c++ 中的十六进制
- 如何在C++中将十六进制字符串转换为文本数据
- 使用 sprintf 将十六进制0xAABBCC转换为字符串"AA:BB:CC"
- 定义宏以将前缀 0x 添加到十六进制字符串文本
- 如何使用 setfill 和 setw 在字符串变量中存储十六进制值
- 将字符串(可以是十进制字符串或十六进制字符串)转换为整数C++
- 在Arduino中将字符串转换为(逗号分隔的十六进制)字符串到无符号字符数组
- 将 std::string( "x3BxDEx7C" ) 转换为可读的十六进制字符串?
- C++ 将十六进制字符串表示形式转换为十六进制字符串表示形式
- 字符数组到十六进制字符串的转换 - 意外输出
- C++将 wwn 字符串转换为识别为十六进制的数据类型
- 将字符串存储为十六进制而不进行转换
- C++:格式化包含十六进制值的字符串
- 字符串十六进制到指针获取值
- 如何从字符串十六进制中获取十进制
- Arduino:将字符串十六进制"#FFFFFF"转换为 3 int