【问题标题】:Converting the stream of bytes into 32 bit unsigned integer将字节流转换为 32 位无符号整数
【发布时间】:2021-05-29 21:16:45
【问题描述】:

我认为这段代码将字节流转换为 32 位无符号整数。但是双指针(**buf)有什么用。我们不能只使用一个指针吗? 有人可以解释一下这段代码 sn-p 是如何与示例一起工作的吗?

uint32_t unpack_u32(const uint8_t **buf) {
    uint32_t val;
    memcpy(&val, *buf, sizeof(uint32_t));
    (*buf) += sizeof(uint32_t);
    return ntohl(val);
}

【问题讨论】:

  • 我个人会使用sizeof(uint32_t); 而不是sizeof(val);

标签: c serialization deserialization


【解决方案1】:

API 以重复形式使用。缓冲区中的指针增加到下一个解包数据。

uint8_t *buf = ...
uint32_t first = unpack_u32(&buf);
uint16_t second = unpack_u16(&buf);
uint32_t third = unpack_u32(&buf);

【讨论】:

  • 是的,是unpack_u32() 中的(*buf) += sizeof(uint32_t); 行将指针移到sizeof(uint32_t) 字节上。
猜你喜欢
  • 1970-01-01
  • 2019-05-30
  • 1970-01-01
  • 2018-03-23
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2017-09-05
相关资源
最近更新 更多