将十六进制字符串转换为字节数组转换可变长度十六进制字符串的最佳方法是什么?"01A1"到包含该数据的字节数组。即转换为:std::string = "01A1";变成这样char* hexArray;int hexLength;或者这个std::vector<char> hexArray;所以当我把这个写到一个文件hexdump -C我得到的二进制数据包含01A1.
4 回答
哈士奇WWW
TA贡献1799条经验 获得超6个赞
#include <cstdint>#include <initializer_list>#include <stdexcept>#include <utility>/* Quick and dirty conversion from a single character to its hex equivelent */constexpr std::uint8_t HexCharToInt(char Input){ return ((Input >= 'a') && (Input <= 'f')) ? (Input - 87) : ((Input >= 'A') && (Input <= 'F')) ? (Input - 55) : ((Input >= '0') && (Input <= '9')) ? (Input - 48) : throw std::exception{};}/* Position the characters into the appropriate nibble */constexpr std::uint8_t HexChar(char High, char Low){ return (HexCharToInt(High) << 4) | (HexCharToInt(Low));}/* Adapter that performs sets of 2 characters into a single byte and combine the results into a uniform initialization list used to initialize T */template <typename T, std::size_t Length, std::size_t ... Index>constexpr T HexString(const char (&Input)[Length], const std::index_sequence<Index...>&){ return T{HexChar(Input[(Index * 2)], Input[((Index * 2) + 1)])...};}/* Entry function */template <typename T, std::size_t Length>constexpr T HexString(const char (&Input)[Length]){ return HexString<T>(Input, std::make_index_sequence<(Length / 2)>{});}constexpr auto Y = KS::Utility::HexString<std::array<std::uint8_t, 3>>("ABCDEF");
蝴蝶刀刀
TA贡献1801条经验 获得超8个赞
BIGNUM *input = BN_new();int input_length = BN_hex2bn(&input, argv[2]);input_length = (input_length + 1) / 2; // BN_hex2bn() returns number of hex digitsunsigned char *input_buffer = (unsigned char*)malloc(input_length);retval = BN_bn2bin(input, input_buffer);
- 4 回答
- 0 关注
- 345 浏览
添加回答
举报
0/150
提交
取消