簡體   English   中英

如何在C ++中將字符串轉換為HexBytes數組?

[英]How to convert a String to a HexBytes Array in C++?

我找不到在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] = '\0';
    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]);
     }

從字符串中一次獲取兩個字符(請參見例如std::string::substr ),然后使用std::stoi轉換為整數值。

首先,您使用的是不健康的C和C ++組合。 嘗試選擇一個並堅持下去(即使用其慣用法)。 您的代碼有內存泄漏,不必要的副本等。

其次,您只需要兩件事:

  1. 一種將兩個連續字符(十六進制數字)轉換為它們的數字對應char我想是一個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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM