C++ byte数组转16进制大写字符串
时间: 2023-07-04 11:31:00 浏览: 74
可以使用以下代码将 C++ 中的 byte 数组转换为 16 进制大写字符串:
```c++
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
int main() {
// 假设有一个 byte 数组
unsigned char bytes[] = {0x12, 0x34, 0xAB, 0xCD};
// 将 byte 数组转换为 16 进制大写字符串
stringstream ss;
ss << hex << uppercase << setfill('0');
for (int i = 0; i < sizeof(bytes); i++) {
ss << setw(2) << static_cast<int>(bytes[i]);
}
string hexStr = ss.str();
// 输出结果
cout << hexStr << endl;
return 0;
}
```
输出结果为 `1234ABCD`。
相关问题
C++ 整数转16进制大写字符串
同样可以使用C++中的stringstream和iomanip库来实现整数转16进制大写字符串的操作,只需要在stringstream对象中加上uppercase修饰符即可。下面是一个示例代码:
```C++
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
int main() {
int num = 123456789; // 待转换的整数
stringstream ss;
ss << hex << uppercase << num; // 将整数以16进制大写格式写入到stringstream对象中
string hex_str = ss.str(); // 从stringstream对象中取出转换后的16进制大写字符串
cout << hex_str << endl; // 输出16进制大写字符串
return 0;
}
```
输出结果为:
```
75BCD15
```
c++ byte字符串转16进制字符串
可以使用stringstream和iomanip库来实现byte字符串转16进制字符串,具体代码如下:
```c++
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
string byteToHexStr(const unsigned char* byte_arr, int arr_len) {
stringstream ss;
ss << hex << setfill('0');
for (int i = 0; i < arr_len; i++) {
ss << setw(2) << static_cast<unsigned>(byte_arr[i]);
}
return ss.str();
}
int main() {
unsigned char byte_arr[] = {0x12, 0x34, 0xAB, 0xCD};
int arr_len = sizeof(byte_arr) / sizeof(byte_arr[0]);
string hex_str = byteToHexStr(byte_arr, arr_len);
cout << hex_str << endl; // 输出 "1234abcd"
return 0;
}
```