简体   繁体   English

序列化:char和uint32_t的大小

[英]Serialization: size of char and uint32_t

I have multiple questions. 我有多个问题。

  1. Is the size of char always 1 (Byte) on every system ? 在每个系统上,char的大小是否始终为1(字节)?
  2. Is the size of uint32_t always 4 (Byte) on every system ? 每个系统上uint32_t的大小是否始终为4(字节)?

I wrote two little functions to serialize my struct, but I can't tell if this is a good way to do it. 我写了两个小函数来序列化我的结构,但是我不知道这是否是个好方法。

struct udtpackage{
    char version;
    bool eof;
    uint32_t data_size;
    uint32_t encrypted_size;
    char data[BUFFERSIZE+16];
    char hmac[64];
};

void serialize (udtpackage package, unsigned char* buffer){
    uint32_t tmp;

    memcpy(&buffer[0], &package.version, 1);
    (package.eof) ? (buffer[1] = 0xFF) : (buffer[1] = 0x00);
    tmp = htonl(package.data_size);
    memcpy(&buffer[2], &tmp, 4);
    tmp = htonl(package.encrypted_size);
    memcpy(&buffer[6], &tmp, 4);
    memcpy(&buffer[10], &package.data[0], BUFFERSIZE+16);
    memcpy(&buffer[10+BUFFERSIZE+16], &package.hmac[0], 64);
}

void deserialize (udtpackage* package, unsigned char* buffer){
    uint32_t tmp;

    memcpy(&package->version, &buffer[0], 1);
    (buffer[1] & 0xFF) ? (package->eof = true) : (package->eof = false);
    memcpy(&tmp, &buffer[2], 4);
    package->data_size = ntohl(tmp);
    memcpy(&tmp, &buffer[6], 4);
    package->encrypted_size = ntohl(tmp);
    memcpy(&package->data[0], &buffer[10], BUFFERSIZE+16);
    memcpy(&package->hmac[0], &buffer[10+BUFFERSIZE+16], 64);
}
  1. Yes. 是。 The size of char is always 1. That doesn't mean that there are 8 bits per byte though. char的大小始终为1。但这并不意味着每个字节有8位。

  2. No. For example, the implementation may define 32 bits per byte, 否。例如,实现可以定义每个字节32位,
    then the size of uint32_t will be 1. If this is the case, some of the fixed width types will not be defined. 那么uint32_t的大小将为1。如果是这种情况,则不会定义某些固定宽度类型。

Here is a potential problem: 这是一个潜在的问题:

memcpy(&buffer[2], &tmp, 4);    
                         ^

As I mentioned in the second point, the code should be: 正如我在第二点提到的那样,代码应为:

memcpy(&buffer[2], &tmp, sizeof(tmp));
                         ^

Going further the buffer offsets should be fixed as well, otherwise you will potentially waste memory: 更进一步,缓冲区偏移也应固定,否则可能会浪费内存:

memcpy(&buffer[6], &tmp, 4);
               ^

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

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