【问题标题】:To Obtain EPOCH Time Value from a Packed BIT Structure in C从 C 中的打包 BIT 结构中获取 EPOCH 时间值
【发布时间】:2012-03-30 07:50:19
【问题描述】:

我需要从具有以下数据结构(它是一个 12 字节结构)的二进制数据文件中找出 Epoch 时间:

Field-1 : Byte 1, Byte 2, + 6 Bits from Byte 3
Time-1  :                   2 Bits from Byte 3 + Byte 4
Time-2  : Byte 5, Byte 6, Byte 7, Byte 8
Field-2 : Byte 9, Byte 10, Byte 11, Byte 12

对于 Field-1 和 Field-2 我没有问题,因为它们可以轻松取出。

我需要 Epoch Time (long) 中的时间值,因为它已打包在字节 5、6、7、8 和 3 和 4 中,如下所示:

  • 字节 5 到 8(32 位字)从 0 到 31 打包时间值位(字节 5 有 0 到 7 位, 字节 6 有 8 到 15,字节 7 有 16 到 23,字节 8 有 24 到 31)。

剩余的 10 位时间值分别打包在 Bytes 3 和 byte 4 中,如下:

  • 字节 3 有 2 位:32 和 33,字节 4 有剩余位:34 到 41。

所以时间值的总位数是 42 位,如上打包。

我需要计算来自这 42 位的 epoch 值。我该怎么做?

我做过类似的事情,但不确定它是否给了我正确的价值:

typedef struct P_HEADER {
    unsigned int tmuNumber : 22; //sorry for the typo.
    unsigned int time1 : 10; // Bits 6,7 from Byte-3 + 8 bits from Byte-4
    unsigned int time2 : 32; // 32 bits: Bytes 5,6,7,8
    unsigned int traceKey : 32; 
} __attribute__((__packed__)) P_HEADER;

然后在代码中:

P_HEADER *header1;

//get input string in hexa,etc..etc..
//parse the input with the header as :
header1 = (P_HEADER *)inputBuf;
// then print the header1->time1, header1->time2 ....
long ttime = header1->time1|header1->time2;

这是获取价值的方式吗?

【问题讨论】:

  • 为什么是 21 位而不是 22 位?当前两个位字段中有 31 位时,packed 会做什么?剩下的两个 32 位字段是否奇怪对齐?
  • 你本地的time_t是32位还是64位的数量?当表示的时间为 1970-01-01 00:00:00+00:00 时,您的 42 位时间值包含什么? 2012-03-29 07:33:55-08:00 它包含什么值?对于 Unix 系统,答案分别是 0 和 1333031635。
  • 首先,我认为 tmuNumber 是 22 位(8+8+6),其次,您想要的 ttime 将是 time1 后跟 ttime2 位,不是吗?那我觉得你需要做以下事情:uint64_t ttime = (((uint64_t)header1->time1) << 32) + ((uint64_t)header1->time2);
  • 我认为这是一个错误的计数,他清楚地描述了填充的第一位是 22 位长。但是,如果我正确理解规范,time1 需要在 `|'ing 之前先换班

标签: c


【解决方案1】:

这将为您提供所描述的价值:

typedef struct P_HEADER {
    unsigned int tmuNumber : 22;
    unsigned int time1 : 10; // Bits 6,7 from Byte-3 + 8 bits from Byte-4
    unsigned int time2 : 32; // 32 bits: Bytes 5,6,7,8
    unsigned int traceKey : 32; 
} __attribute__((__packed__)) P_HEADER;

long ttime = ((uint64_t)header1->time1) << 32 | header1->time2;

不过,只能在 little-endian 机器上这样工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 2011-12-16
    • 2019-07-16
    • 2021-04-07
    • 2023-04-02
    • 2017-10-16
    相关资源
    最近更新 更多