C ++ newbie here。
我有3个字符串
const char section1[] = {0x12, 0x34, 0x56, 0x78};
std::wstring section2 = L"section2";
const char section3[] = {0x23, 0x45, 0x67, 0x89};
我需要将它们加在一起,结果看起来像
{0x12,0x34,0x56,0x78,0x73,0x00,0x65,0x00,0x63,0x00,0x74,0x00,0x69,0x00,0x6f 0x6e,0x00,0x32,0x00,0x23,0x45,0x67,0x89} < / p>
因此,两个带有Unicode部分的ASCII位夹在中间。 加入它们的最佳方式是什么,以及要输出到文件的最佳数据类型是什么?
答案 0 :(得分:2)
std::vector<unsigned char> Buffer;
for (size_t i = 0; i < sizeof(section1); ++i)
Buffer.push_back((unsigned char) section1[i]);
for (size_t i = 0; i < section2.size(); ++i) {
unsigned short u = (unsigned short) section2[i];
Buffer.push_back((unsigned char) (u >> 8));
Buffer.push_back((unsigned char) (u & 0xFF));
}
for (size_t i = 0; i < sizeof(section3); ++i)
Buffer.push_back((unsigned char) section31[i]);
您还可以将memcpy用于第1节和第3节,如果您也对第2节的字节顺序进行了假设。上面的循环应该易于阅读和理解。
完成后,您只需从&amp; Buffer [0]
开始写入Buffer.size()字节