为了账号安全,请及时绑定邮箱和手机立即绑定

将十六进制字符串转换为字节数组

将十六进制字符串转换为字节数组

C++
阿波罗的战车 2019-07-20 14:17:08
将十六进制字符串转换为字节数组转换可变长度十六进制字符串的最佳方法是什么?"01A1"到包含该数据的字节数组。即转换为:std::string = "01A1";变成这样char* hexArray;int hexLength;或者这个std::vector<char> hexArray;所以当我把这个写到一个文件hexdump -C我得到的二进制数据包含01A1.
查看完整描述

4 回答

?
神不在的星期二

TA贡献1963条经验 获得超6个赞

所以为了好玩,我很好奇我是否能在编译时完成这种转换。它没有太多的错误检查,并且是在VS 2015中完成的,它还不支持C+14 Conexpr函数(这就是HexCharToInt的样子)。它采用c-字符串数组,将一对字符转换为单个字节,并将这些字节展开为一个统一的初始化列表,用于初始化作为模板参数提供的T类型。T可以替换为像std:Array这样的东西来自动返回数组。

#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");



查看完整回答
反对 回复 2019-07-20
?
MMMHUHU

TA贡献1834条经验 获得超8个赞

如果您想使用OpenSSL来完成它,我发现了一个巧妙的技巧:

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);

只需确保去掉任何引导‘0x’到字符串。


查看完整回答
反对 回复 2019-07-20
  • 4 回答
  • 0 关注
  • 1430 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信