[英]Reading a 4 bytes date (big endian) from binary file
I have a date encoded (big endian) in 4 bytes that I'm trying to read from a binary file. 我尝试从二进制文件中读取一个4字节的日期编码(大端)。
I do: 我做:
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));
But I get: 但是我得到:
Thu Jan 1 00:59:27 1970
What's wrong with my code ? 我的代码有什么问题? Thanks.
谢谢。
(date[0]<<32);
looks wrong. 看起来错了。
16 + 8
is 24
not 32
. 16 + 8
是24
而不是32
。
You can reduce your code complexity by using ntohl(3)
: 您可以使用
ntohl(3)
降低代码复杂度:
#include <arpa/inet.h>
/* ... */
uint32_t date;
s = read(fd, &date, sizeof(date));
seconds = ntohl(date);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.