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

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

// 将字节流转换为十六进制数的字符串
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创建的十六进制字符串转换为字节流形式
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;
}

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;
}
posted @ 2024-05-20 11:39  卡尔的思索  阅读(18)  评论(0编辑  收藏  举报