【问题标题】:Reading a 4 bytes date (big endian) from binary file从二进制文件中读取 4 字节日期(大端)
【发布时间】:2013-12-06 18:51:39
【问题描述】:

我尝试从二进制文件中读取一个以 4 个字节编码的日期(大端序)。

我愿意:

char date[4];
long seconds;
s = read(fd, date, sizeof(char) * 4);
seconds = (date[3]<<0) | (date[2]<<8) | (date[1]<<16) | (date[0]<<32);

printf("%s\n", ctime(&seconds));

但我明白了:

Thu Jan  1 00:59:27 1970

我的代码有什么问题?谢谢。

【问题讨论】:

  • 你的系统是小端吗?
  • OT:sizeof(char) 根据定义等于 1。

标签: c date gcc compiler-construction endianness


【解决方案1】:
(date[0]<<32);

看起来不对。 16 + 824 不是 32

【讨论】:

  • 如果 date[3] = -128,seconds = (date[3]&lt;&lt;0) 不会变成 0xFFFFFF80 吗? date 不应该是无符号数组吗?
【解决方案2】:

你可以使用ntohl(3)来降低你的代码复杂度:

#include <arpa/inet.h>
/* ... */
uint32_t date;
s = read(fd, &date, sizeof(date));
seconds = ntohl(date);

【讨论】:

  • 就是这样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-11
  • 1970-01-01
  • 2013-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
相关资源
最近更新 更多