字节流与十六进制字符串的相互转化

#include <iostream>
#include <vector>
#include <cassert>

using Digest = std::vector<unsigned char>;

int hexCharToDecimal(unsigned char digest)
{
	int ch = 0;
	if (digest >= '0' && digest <= '9')
		ch = digest - '0';
	else if (digest >= 'a' && digest <= 'f')
		ch = digest - 'a' + 10;
	else if (digest >= 'A' && digest <= 'F')
		ch = digest - 'A' + 10;
	else
		return -1;
	return ch;
}

// 将字节流转换为十六进制数的字符串
std::string digestToHex(const Digest& bytes, size_t length)
{
	static const char digits[] = "0123456789abcdef";
	const size_t fullLen = bytes.size() * 2;
	size_t len = length ? length * 2 : fullLen;
	if (len > fullLen)
		return "";
	std::string result;
	result.reserve(len);
	for (auto b : bytes) {
		result += digits[(b >> 4) & 0xF];
		result += digits[b & 0xF];
		if (result.size() >= len) break;
	}
	return result;
}

// 将digestToHex创建的十六进制字符串转换为字节流形式
bool digestFromHex(const std::string& digest, Digest& result)
{
	if (digest.size() % 2 != 0) {
		return false;
	}
	result.reserve(digest.size() / 2);
	for (size_t i = 0; i < digest.size(); i += 2) {
		int a = hexCharToDecimal(digest[i]);
		int b = hexCharToDecimal(digest[i + 1]);
		if (a == -1 || b == -1) {
			return false;
		}
		result.emplace_back(static_cast<unsigned char>((a << 4) + b));
	}
	return true;
}


// 测试 hexCharToDecimal 函数
void testHexCharToDecimal() {
	assert(hexCharToDecimal('0') == 0);
	assert(hexCharToDecimal('9') == 9);
	assert(hexCharToDecimal('a') == 10);
	assert(hexCharToDecimal('f') == 15);
	assert(hexCharToDecimal('A') == 10);
	assert(hexCharToDecimal('F') == 15);
	assert(hexCharToDecimal('g') == -1); // 无效字符
	assert(hexCharToDecimal('Z') == -1); // 无效字符
	std::cout << "testHexCharToDecimal passed" << std::endl;
}

// 测试 digestToHex 函数
void testDigestToHex() {
	Digest digest1 = { 0xab, 0xcd, 0xef };
	assert(digestToHex(digest1, digest1.size()) == "abcdef");

	Digest digest2 = { 0x1, 0x23, 0x45, 0x67 };
	assert(digestToHex(digest2, 2) == "0123");

	std::cout << "testDigestToHex passed" << std::endl;
}

// 测试 digestFromHex 函数
void testDigestFromHex() {
	std::string hex1 = "abcdef";
	Digest result1;
	assert(digestFromHex(hex1, result1));
	assert(result1 == Digest({ 0xab, 0xcd, 0xef }));

	std::string hex2 = "0123";
	Digest result2;
	assert(digestFromHex(hex2, result2));
	assert(result2 == Digest({ 0x01, 0x23 }));

	std::string hex3 = "ghijkl"; // 无效的十六进制字符串
	Digest result3;
	assert(!digestFromHex(hex3, result3));

	std::cout << "testDigestFromHex passed" << std::endl;
}

int main() {
	testHexCharToDecimal();
	testDigestToHex();
	testDigestFromHex();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值