我试图通过修改秒的定义(长时间无符号的 n_ticks_per_second)来改进SWRTC,方法是与服务器同步时间。
#include <stdint.h>
#include <stdio.h>
int main(int argc, char * argv[]){
int32_t total_drift_SEC;
int32_t drift_per_sec_TICK;
uint32_t at_update_posix_time = 1491265740;
uint32_t posix_time = 1491265680;
uint32_t last_update_posix_time = 1491251330;
long unsigned n_ticks_per_sec = 1000;
total_drift_SEC = (posix_time - at_update_posix_time);
drift_per_sec_TICK = ((float) total_drift_SEC) / (at_update_posix_time - last_update_posix_time);
n_ticks_per_sec += drift_per_sec_TICK;
printf("Total drift sec %d\r\n", total_drift_SEC);
printf("Drift per sec in ticks %d\r\n", drift_per_sec_TICK);
printf("n_ticks_per_second %lu\r\n", n_ticks_per_sec);
return 0;
}我不明白的是,我需要将total_drift_SEC转换为float,以便最终得到一个正确的结果(即最终n_ticks_per_sec等于1000 )。
此代码的输出是:
总漂移秒-60 以滴答数计每秒漂移0 n_ticks_per_second 1000
而代码的输出没有要浮动的强制转换,则是:
总漂移秒-60 以滴答声计每秒漂移298054 n_ticks_per_second 299054
发布于 2017-04-04 13:12:39
这条线
drift_per_sec_TICK = total_drift_SEC / (at_update_posix_time - last_update_posix_time);将32位signed int除以32位unsigned int。
32位unsigned int比32位signed int具有更高的等级。
在执行算术操作时,应用“常规算术转换”:
来自C11标准草案6.3.1.8/1
如果具有无符号整数类型的操作数的秩大于或等于另一个操作数类型的秩,则带符号整数类型的操作数转换为无符号整数类型的操作数类型。
因此,-60被转换为(32位) unsigned int:4294967236
这里
drift_per_sec_TICK = (float) total_drift_SEC / (at_update_posix_time - last_update_posix_time);适用于以下情况(取自上文C标准的段落):
如果任何一个操作数的对应实类型是浮动的,则另一个操作数在不改变类型域的情况下转换为相应的实类型为
float的类型。
为了不盲目地踏入这些陷阱,在与GCC一起编译时,一定要指定-Wconversion。
https://stackoverflow.com/questions/43207493
复制相似问题