Converting a hex string to a byte array

后端 未结 19 2167
时光取名叫无心
时光取名叫无心 2020-11-22 12:10

What is the best way to convert a variable length hex string e.g. \"01A1\" to a byte array containing that data.

i.e converting this:

st         


        
19条回答
  •  旧巷少年郎
    2020-11-22 13:10

    #include 
    
    using byte = unsigned char;
    
    static int charToInt(char c) {
        if (c >= '0' && c <= '9') {
            return c - '0';
        }
        if (c >= 'A' && c <= 'F') {
            return c - 'A' + 10;
        }
        if (c >= 'a' && c <= 'f') {
            return c - 'a' + 10;
        }
        return -1;
    }
    
    // Decodes specified HEX string to bytes array. Specified nBytes is length of bytes
    // array. Returns -1 if fails to decode any of bytes. Returns number of bytes decoded
    // on success. Maximum number of bytes decoded will be equal to nBytes. It is assumed
    // that specified string is '\0' terminated.
    int hexStringToBytes(const char* str, byte* bytes, int nBytes) {
        int nDecoded {0};
        for (int i {0}; str[i] != '\0' && nDecoded < nBytes; i += 2, nDecoded += 1) {
            if (str[i + 1] != '\0') {
                int m {charToInt(str[i])};
                int n {charToInt(str[i + 1])};
                if (m != -1 && n != -1) {
                    bytes[nDecoded] = (m << 4) | n;
                } else {
                    return -1;
                }
            } else {
                return -1;
            }
        }
        return nDecoded;
    }
    
    int main(int argc, char* argv[]) {
        if (argc < 2) {
            return 1;
        }
    
        byte bytes[0x100];
        int ret {hexStringToBytes(argv[1], bytes, 0x100)};
        if (ret < 0) {
            return 1;
        }
        std::cout << "number of bytes: " << ret << "\n" << std::hex;
        for (int i {0}; i < ret; ++i) {
            if (bytes[i] < 0x10) {
                std::cout << "0";
            }
            std::cout << (bytes[i] & 0xff);
        }
        std::cout << "\n";
    
        return 0;
    }
    

提交回复
热议问题