c++ unsigned char 按照十六进制输出成字符串
可以使用stringstream和iomanip库来实现将unsigned char类型按照十六进制输出成字符串的功能。
示例代码:
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
int main()
{
unsigned char data[] = {0x48, 0x65, 0x6c, 0x6c, 0x6f}; // "Hello"的十六进制表示
stringstream ss;
for (int i = 0; i < sizeof(data) / sizeof(unsigned char); i++)
{
ss << setfill('0') << setw(2) << hex << (int)data[i]; // 将每个unsigned char按照十六进制格式输出并拼接成字符串
}
string result = ss.str(); // stringstream转换成字符串
cout << result << endl; // 输出结果:"48656c6c6f"
return 0;
}
在上述代码中,使用了stringstream和iomanip库来实现将unsigned char类型按照十六进制输出成字符串的功能。具体实现步骤如下:
-
定义unsigned char类型的数组data,包含需要转换为字符串的数据。
-
创建一个stringstream对象ss。
-
使用for循环遍历data数组中的每个元素,将每个unsigned char按照十六进制格式输出并拼接成字符串,最终得到的字符串存储在stringstream对象ss中。
-
将stringstream对象ss转换成字符串,存储在string类型变量result中。
-
输出结果字符串result。
在上述代码中,setfill('0')和setw(2)用于控制输出的格式,保证每个unsigned char按照两位十六进制格式输出。如果需要输出的unsigned char不足两位,则在前面用0填充
原文地址: https://www.cveoy.top/t/topic/eN4n 著作权归作者所有。请勿转载和采集!