[英]Memcpy uint32_t into char*
我用不同的格式和类似的东西进行了一些测试。 我们得到了一个必须将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很简单,我们必须在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,然后对我来说是一些随机数..我在做什么错?
假设string
为std::string
,则使用std::string::append
的单参数版本,假定输入数据为NUL终止。 您的不是,但是append
仍然会寻找第一个NUL字节。
512是0x00000100,在小端机器上是0x00 0x01 0x00 0x00。 由于第一个字节为NUL,因此std::string::append()
在那里停止。
使用传递长度的std::string::append()
版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.