如何在C++中将字符串转换为HexBytes数组

How to convert a String to a HexBytes Array in C++?

本文关键字:转换 HexBytes 数组 字符串 C++      更新时间:2023-10-16

我在C++中找不到将字符串转换为十六进制字节数组的方法,我在C#中只有一个例子:

public static byte[] ToBytes(string input)
{
   byte[] bytes = new byte[input.Length / 2];
   for (int i = 0, j = 0; i < input.Length; j++, i += 2)
      bytes[j] = byte.Parse(input.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
   return bytes;
}

我试过这种方式

byteRead = "02000000ce1eb94f04b62e21dba62b396d885103396ed096fbb6c1680000000000000000223cc23c0df07a75eff6eabf22d6d5805105deff90f1617f27f58045352b31eb9d0160538c9d001900000000";
    // BYTES HEX
    char *hexstring = new char[byteRead.length()+1];
    strcpy(hexstring,byteRead.c_str());       
    uint8_t str_len = strlen(hexstring);       
    for (i = 0; i < (str_len / 2); i++) {
       sscanf(hexstring + 2*i, "%02x", &bytearray[i]);
    }

更新

这里有一个解决方案,这项工作为我在Arduino Uno:

char hexstring[] = "020000009ecb752aac3e6d2101163b36f3e6bd67d0c95be402918f2f00000000000000001036e4ee6f31bc9a690053320286d84fbfe4e5ee0594b4ab72339366b3ff1734270061536c89001900000000";
    int i;
    int bytearray[80];
    char tmp[3];
    tmp[2] = '';
    int j = 0;
    for(i=0;i<strlen(hexstring);i+=2) {
        tmp[0] = hexstring[i];
        tmp[1] = hexstring[i+1];
        bytearray[j] = strtol(tmp,0,16);
        j+=1;
     }
    for(i=0;i<80;i+=1) {
       Serial.println(bytearray[i]);
     }

首先,您使用的是不健康的C和C++混合;试着选择其中一个并坚持下去(也就是说,使用它的习语(。你的代码有内存泄漏、不必要的副本等…

其次,你只需要两样东西:

  1. 一种将两个连续字符(十六进制数字(转换为数字对应字符的方法(我想是char?(
  2. 存储连续转换的方法

首先,虽然确实可以使用sscanf,但C++倾向于使用istream,尽管这很棘手,因为没有"停止";所以我们可以手动完成:

char fromHexadecimal(char const digit) {
    if ('0' <= digit and digit <= '9') { return digit - '0'; }
    if ('a' <= digit and digit <= 'f') { return 10 + digit - 'a'; }
    if ('A' <= digit and digit <= 'F') { return 10 + digit - 'A'; }
    throw std::runtime_error("Unknown hexadecimal digit");
}
char fromHexadecimal(char digit0, char digit1) {
    return fromHexadecimal(digit0) * 16 + fromHexadecimal(digit1);
}

有了这个障碍,我们就可以同时使用字符串进行输入和输出;毕竟,string只是char:的集合

std::string fromHexadecimal(std::string const& hex) {
    if (hex.size() % 2 != 0) {
        throw std::runtime_error("Requires an even number of hex digits");
    }
    std::string result;
    for (size_t i = 0, max = hex.size() / 2; i != max; ++i) {
        result.push_back(fromHexadecimal(hex.at(2*i), hex.at(2*i+1)));
    }
    return result;
}

一次从字符串中获取两个字符(例如参见std::string::substr(,并使用std::stoi转换为整数值。