如何从s64值中删除前3个字节和最后一个字节?
代码:
s64 end_time; struct timespec ts; getrawmonotonic(&ts); end_time = timespec_to_ns(&ts);
如何从end_time
删除前三个字节并从中end_time
最后一个字节? 我想将它存储在uint32中。 谁能告诉我怎么做?
uint32 latency; fscanf(fp, "%lu\n", latency); //fp is reading the end_time and storing in latency. latency = (uint32) (latency >> 8) & 0xFFFFFFFF;
怎么样:
u32 end_time32 = (u32) (end_time >> 24) & 0xFFFFFFFF;
根据您对first
和last
字节的定义,它也可以是:
u32 end_time32 = (u32) (end_time >> 8) & 0xFFFFFFFF;
例:
s64 end_time = 0x1234567890ABCDEF; u32 end_time32 = (u32) (end_time >> 24) & 0xFFFFFFFF; // end_time32 is now: 0x34567890 s64 end_time = 0x1234567890ABCDEF; u32 end_time32 = (u32) (end_time >> 8) & 0xFFFFFFFF; // end_time32 is now: 0x7890ABCD
编辑
更新后的问题:
s64 latency; fscanf(fp, "%lld", latency); //fp is reading the end_time and storing in latency. u32 latency32 = (uint32) (latency >> 8) & 0xFFFFFFFF;
我假设“第一”和“最后”分别表示“最重要”和“最不重要”。
即,你有8个字节:
76543210
并希望将其映射到4个字节:
4321
这是最容易通过移位,蒙版和(截断)强制转换完成的:
const uint32_t time32 = (uint32_t) ((end_time >> 8) & 0xffffffff);
掩码很可能由编译器优化,但很清楚发生了什么。
你可以用位移来做到这一点 。 您必须将值8位(= 1个字节)向右移动,这是通过>>
运算符完成的:
uint32_t t = (uint32_t)(end_time >> 8); // ^^ // bit-shifting
在下文中,可视化字节以便更好地理解。 如果值end_time
由八个字节组成,符号值为ABCDEFGH
,那么你想要的是DEFG
:
end_time: ABCDEFGH end_time >> 8: 0 ABCDEFG (uint32_t)(end_time >> 8): DEFG