c++ 16进制字符串转 2进制数组
#include <iostream>
#include <time.h>
#include <vector>
#include <algorithm>
vector<uint8_t> hex_str_to_byte(std::string hexstr)
{
vector<uint8_t> bakval;
uint8_t val = 0;
char tmpal = 0;
transform(hexstr.begin(), hexstr.end(), hexstr.begin(), ::toupper);
auto list = split(hexstr, " ");
for (size_t i = 0; i < list.size(); i++)
{
if (list[i].size() == 2)
{
tmpal = list[i][0];
if (tmpal >= 'A' && tmpal <= 'F')
val = (tmpal - 'A' + 10) << 4;
else
val = (tmpal & ~0x30) << 4;
tmpal = list[i][1];
//处理后4位, 并组合起来
if (tmpal >= 'A' && tmpal <= 'F')
val |= (tmpal - 'A' + 10) & 0x0f;
else
val |= (tmpal & ~0x30);
bakval.push_back(val);
}
}
return bakval;
}
c++ 数组转16进制字符串
#include <iostream>
#include <time.h>
#include <vector>
#include <algorithm>
//
void _char_to_hex(unsigned char src, unsigned char* out_hex16)
{
static char hex_table[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
out_hex16[0] = hex_table[src >> 4];
out_hex16[1] = hex_table[src & 0x0f];
out_hex16[2] = '\0';
}
std::string byteToHexStr(std::vector<uint8_t> &hex,std::string heade = "0x")
{
std::string bak;
unsigned char out_hex[3] = {0};
for (size_t i = 0; i < hex.size(); i++)
{
_char_to_hex(hex[i], out_hex);
bak += heade;
bak += out_hex[0];
bak += out_hex[1];
bak += " ";
//std::cout << out_hex << " ";
}
return bak;
}