亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將十六進制字符串轉換為字節數組

將十六進制字符串轉換為字節數組

C++
翻翻過去那場雪 2019-08-03 03:03:07
將十六進制字符串轉換為字節數組轉換可變長度十六進制字符串的最佳方法是什么?"01A1"到包含該數據的字節數組。即轉換為:std::string = "01A1";變成這樣char* hexArray;int hexLength;或者這個std::vector<char> hexArray;所以當我把這個寫到一個文件hexdump -C我得到的二進制數據包含01A1.
查看完整描述

4 回答

?
哈士奇WWW

TA貢獻1799條經驗 獲得超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-08-04
?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超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-08-04
  • 4 回答
  • 0 關注
  • 381 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號