C++对数据进行16进制编码&解码(hex encode)

本例演示使用16进制对数据进行编码

先定义几个工具函数用于将数字转为16进制表示或者将16进制表示转换为数字:


//* 将数字转为16进制(大写)
inline char ToHexUpper(unsigned int value) 
{
	return "0123456789ABCDEF"[value & 0xF];
}

//* 将数字转为16进制(小写)
inline char ToHexLower(unsigned int value) 
{
	return "0123456789abcdef"[value & 0xF];
}

//* 将数16进(大写或小写)制转为数字
inline int FromHex(unsigned int c) 
{
	return ((c >= '0') && (c <= '9')) ? int(c - '0') :
		((c >= 'A') && (c <= 'F')) ? int(c - 'A' + 10) :
		((c >= 'a') && (c <= 'f')) ? int(c - 'a' + 10) :
		/* otherwise */              -1;
}

 

将数据进行16进制编码:

//* 将数据d用16进制编码,返回值即是结果
std::string HexEncode(const std::string& d)
{
	std::string hex;
	hex.resize(d.size() * 2);
	char* pHexData = (char*)hex.data();
	const unsigned char* pSrcData = (const unsigned char*)d.data();
	for(int i = 0; i < d.size(); i++)
	{
		pHexData[i*2]     = ToHexLower(pSrcData[i] >> 4);
		pHexData[i*2 + 1] = ToHexLower(pSrcData[i] & 0xf);
	}

	return hex;
}

 

将数据按照16进制解码

//* 将数据d用16进制解码,返回值即是结果
std::string HexDecode(const std::string& hex)
{
	std::string res;
	res.resize(hex.size() + 1 / 2);
	unsigned char* pResult = (unsigned char*)res.data() + res.size();
	bool odd_digit = true;

	for(int i = hex.size() - 1; i >= 0; i--)
	{
		unsigned char ch = unsigned char(hex.at(i));
		int tmp = FromHex(ch);
		if (tmp == -1)
			continue;
		if (odd_digit) {
			--pResult;
			*pResult = tmp;
			odd_digit = false;
		} else {
			*pResult |= tmp << 4;
			odd_digit = true;
		}
	}

	res.erase(0, pResult - (unsigned char*)res.data());

	return res;
}

 

使用举例:

std::string str = "你好世界。";
printf("%s\n", str.c_str());

std::string str_hex = HexEncode(str);
printf("%s\n", str_hex.c_str());

std::string str_from_hex = HexDecode(str_hex);
printf("%s\n", str_from_hex.c_str());

结果:

  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值