简体   繁体   English

Memcpy uint32_t转换为char *

[英]Memcpy uint32_t into char*

I testing a bit with different formats and stuff like that. 我用不同的格式和类似的东西进行了一些测试。 And we got a task where we have to put uint32_t into char*. 我们得到了一个必须将uint32_t放入char *的任务。 This is the code i use: 这是我使用的代码:

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);
}

From string to char is simple and we have to add multiple uints into the char*. 从字符串到char很简单,我们必须在char *中添加多个uint。 So now i'm just calling it like: 所以现在我只是这样称呼它:

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

I absolutely don't understand why the last one isn't working properly. 我绝对不明白为什么最后一个不能正常工作。 I've tested multiple variations of transform this. 我已经测试了转换的多种变体。 One way always gave me output like (in bits): 00110100 | 一种方式总是给我输出(以位为单位):00110100 | 00110101 ... so the first 2 bits are always zero, followed by 11 and then for me some random numbers.. What am i doing wrong? 00110101 ...因此,前2位始终为零,其后为11,然后对我来说是一些随机数..我在做什么错?

Assuming that string is std::string , then the single-argument version of std::string::append is being used, which assumes the input data is NUL-terminated. 假设stringstd::string ,则使用std::string::append的单参数版本,假定输入数据为NUL终止。 Yours is not, but append will go looking for the first NUL byte anyway. 您的不是,但是append仍然会寻找第一个NUL字节。

512 is 0x00000100, which on a little endian machine is 0x00 0x01 0x00 0x00. 512是0x00000100,在小端机器上是0x00 0x01 0x00 0x00。 Since the first byte is NUL, std::string::append() stops there. 由于第一个字节为NUL,因此std::string::append()在那里停止。

Use the version of std::string::append() where you pass in the length. 使用传递长度的std::string::append()版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM