【问题标题】:Memcpy uint32_t into char*Memcpy uint32_t 转换为 char*
【发布时间】:2018-04-30 10:46:18
【问题描述】:

我用不同的格式和类似的东西进行了一些测试。我们有一个任务,我们必须将 uint32_t 放入 char*。这是我使用的代码:

void appendString(string *s, uint32_t append){
    char data[4];
    memcpy(data, &append, sizeof(append));
    s->append(data);
}

void appendString(string *s, short append){
    char data[2];
    memcpy(data, &append, sizeof(append));
    s->append(data);
}

从字符串到字符很简单,我们必须在 char* 中添加多个 uint。所以现在我只是这样称呼它:

string s;
appendString(&s, (uint32_t)1152); //this works
appendString(&s, (uint32_t)640); //this also works
appendString(&s, (uint32_t)512); //this doesn't work

我完全不明白为什么最后一个不能正常工作。我已经测试了变换这个的多种变体。一种方法总是给我输出(以位为单位):00110100 | 00110101 ...所以前 2 位始终为零,然后是 11,然后对我来说是一些随机数。我做错了什么?

【问题讨论】:

  • s->append 怎么知道有多少数据?模板化了吗?
  • 数据没有被“\0”终止。
  • 为什么要使用std::string 处理二进制数据? Append 假设它是一个 C 风格的字符串 - 即 null 终止
  • 二进制数据不要使用std::string,而是使用std::vector<uint8_t>
  • @BenVoigt 我知道它可以,但是std::string 有太多的基于零的字符串的链接,使用向量会更不容易出错。例如,您可以覆盖std::ostream::operator<< 以正确转储二进制数据,但它会拒绝打印等。

标签: c++ arrays char memcpy uint32


【解决方案1】:

假设stringstd::string,则使用std::string::append 的单参数版本,它假设输入数据是NUL 终止的。你的不是,但append 无论如何都会去寻找第一个 NUL 字节。

512 是 0x00000100,在小端机器上是 0x00 0x01 0x00 0x00。由于第一个字节为 NUL,std::string::append() 停在那里。

使用您传递长度的std::string::append() 版本。

【讨论】:

  • 谢谢,成功了!现在我觉得dump^^很简单,但很容易忘记。
猜你喜欢
  • 2012-05-25
  • 1970-01-01
  • 2020-11-10
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
  • 1970-01-01
  • 2017-08-14
  • 1970-01-01
相关资源
最近更新 更多