C++中如何将unsigned char 0xFF转为"FF"及哈希结果转字符串
C++字节与哈希值转十六进制字符串的实现
1. 单个unsigned char转十六进制字符串
把unsigned char 0xFF转成"FF"有几种常用实现方式:
方法1:C风格snprintf
简单直接,适合快速实现:
#include <cstdio> #include <string> unsigned char c = 0xFF; char buf[3]; // 两位字符+结束符 snprintf(buf, sizeof(buf), "%02X", c); std::string str(buf);
%02X指定输出两位大写十六进制,不足补0;unsigned char会被隐式转成int,避免符号问题。
方法2:C++ stringstream(类型安全)
更符合C++现代风格,无需手动管理缓冲区:
#include <sstream> #include <string> #include <iomanip> unsigned char c = 0xFF; std::stringstream ss; ss << std::uppercase << std::setw(2) << std::setfill('0') << static_cast<int>(c); std::string str = ss.str();
static_cast<int>(c)确保按数值而非字符输出;std::uppercase控制大写,setw和setfill保证固定两位长度。
方法3:手动查表(性能优先)
适合对性能要求高的场景,无库函数调用开销:
#include <string> const char hex_chars[] = "0123456789ABCDEF"; unsigned char c = 0xFF; std::string str; str += hex_chars[(c >> 4) & 0x0F]; // 提取高4位对应字符 str += hex_chars[c & 0x0F]; // 提取低4位对应字符
2. 哈希值(字节数组)转字符串
哈希值通常是unsigned char数组(比如MD5为16字节、SHA256为32字节),只需批量处理每个字节即可:
方法1:stringstream批量处理
#include <sstream> #include <string> #include <iomanip> // 假设hash数组已通过Hash函数填充完成 unsigned char hash[32]; std::stringstream ss; ss << std::uppercase; for (size_t i = 0; i < sizeof(hash); ++i) { ss << std::setw(2) << std::setfill('0') << static_cast<int>(hash[i]); } std::string hash_str = ss.str();
方法2:手动查表批量处理(最优性能)
#include <string> const char hex_chars[] = "0123456789ABCDEF"; unsigned char hash[32]; // 已填充的哈希数组 std::string hash_str; hash_str.reserve(sizeof(hash) * 2); // 预分配足够空间,避免频繁扩容 for (size_t i = 0; i < sizeof(hash); ++i) { hash_str += hex_chars[(hash[i] >> 4) & 0x0F]; hash_str += hex_chars[hash[i] & 0x0F]; }
注意事项
- 若需要小写十六进制,移除
std::uppercase,或把hex_chars改为"0123456789abcdef"。 - 绝对不能直接把哈希数组当作C风格字符串使用(哈希值可能包含
'\0',会导致字符串截断)。
内容的提问来源于stack exchange,提问作者GKdhuster
相关产品推荐
相关产品推荐

