【发布时间】:2021-07-18 06:40:43
【问题描述】:
我尝试将 unsigned char 数组转换为大小为 16 的 std::string。 但我不知道为什么结果字符串大小不同。 我想知道原因。
#include <iostream>
using namespace std;
const unsigned char t[16] = { 0x1E, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 ,0x08 ,0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15 };
const unsigned char t2[16] = { 0x1E, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 ,0x08 ,0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15 };
const unsigned char t3[16] = { 0x44, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 ,0x68 ,0x69, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65 };
int main() {
string a, a2, a3;
a = static_cast<std::string>(reinterpret_cast<const char*>(t));
a2.assign(reinterpret_cast<const char*>(t2), 16);
a3.assign(reinterpret_cast<const char*>(t3));
cout << "size : " << a.size() << endl;
for (int i = 0; i < a.size(); i++)
printf("0x%02X ", a.c_str()[i]);
cout << endl << endl;
cout << "size2 : " << a2.size() << endl;
for (int i = 0; i < a2.size(); i++)
printf("0x%02X ", a2.c_str()[i]);
cout << endl << endl;
cout << "size3 : " << a3.size() << endl;
for (int i = 0; i < a3.size(); i++)
printf("0x%02X ", a3.c_str()[i]);
cout << endl << endl;
return 0;
}
结果
尺寸:56
0x1E 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x10 0x11 0x12 0x13 0x14 0x15 0x1E 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x10 0x11 0x12 0x13 0x14 0x15 0x44 0x41 0x42 0x43 0x44 0x45 0x46 0x47 0x68 0x69 0x60 0x61 0x62 0x63 0x64 0x65 0x5F 0x41 0x72 0x67 0x4C 0x69 0x73 0x74
大小2:16
0x1E 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x10 0x11 0x12 0x13 0x14 0x15
size3 : 24
0x44 0x41 0x42 0x43 0x44 0x45 0x46 0x47 0x68 0x69 0x60 0x61 0x62 0x63 0x64 0x65 0x5F 0x41 0x72 0x67 0x4C 0x69 0x73 0x74
【问题讨论】:
-
From cpprefernce 过载
(6):Replaces the contents with those of null-terminated character string pointed to by s。您的输入是 null-terminated 字符串吗? -
@KamilCuk 我曾尝试将作为 aes128 键的字节数组转换为字符串。所以字节数组中不存在空终止字符。感谢您指出并让我知道。
-
`aes128 key to string`的字节数组`那为什么是字符串呢?字符串用于以零结尾的数据。只需使用无符号字符向量即可。
标签: c++