【问题标题】:string size after converting const unsigned char[] to std::string将 const unsigned char[] 转换为 std::string 后的字符串大小
【发布时间】: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++


【解决方案1】:

案例 1:输入没有显式地以空值结尾,并且可能这些全局数组按顺序放置在内存中,因此您至少得到 48 个不带零的字节,最后它在前面 8 个字节找到一些零,因此总数为 56。

案例2:在这里你给它明确的长度,这是在空终止符不存在的情况下做事的正确方法。

案例 3:类似于案例 1,但只是从数组 3 开始,并且需要相同的额外 8 个字节,直到在某处找到空终止符。

解决方案:添加空终止符(零字节)或使用具有明确长度规范的变体。

【讨论】:

  • 我错过了 std::string 中以空字符结尾的字符的概念。感谢您的完美解释。
猜你喜欢
  • 1970-01-01
  • 2013-07-18
  • 2018-09-18
  • 1970-01-01
  • 2010-10-22
  • 1970-01-01
  • 2011-07-23
  • 2012-11-04
  • 2011-05-26
相关资源
最近更新 更多