#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;
}
字节流与十六进制字符串的相互转化
于 2022-11-15 10:10:28 首次发布