c++ 16进制字符串转 2进制数组 和 c++ 数组转16进制字符串

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值