在时间戳中将秒转换为纳秒并使用有符号整数表示

时间:2017-08-22 19:19:42

标签: c if-statement timestamp

这是我的代码:

#include<stdio.h>

typedef unsigned int uint32;
typedef unsigned short int uint16;

typedef signed short int sint32;

#define MAX_NS 999999999
#define MAX_S  4294967295

typedef struct
{
   sint64 nanoseconds;  
   sint64 seconds; 
}TimeStampType;

TimeStampType timeStamp;

sint32 timeStampDifference;

 void GetTimeStamp(sint32* timeStampDifference)
{
        /* Since the range of signed int32 (sint32) is -2147483647 to        +2147483647 timestamp values can not be represented if it exceeds 3 seconds 
 or 2 seconds and 147483647 nanoseconds */

    if((timeStamp.seconds > 3)||(timeStamp.seconds < -3)||((timeStamp.seconds == 2)&&(timeStamp.nanoseconds > 147483647))||((timestamp.seconds == -2)&&(timeStamp.nanoseconds< -147483647))){

        printf("TimeStamp value can not be represented since it overflows");    
    }

    else{

        *timeStampDifference = ((timeStamp.seconds)*(MAX_NS+1)
                         +(timeStamp.nanoseconds));
    }

}

我想要做的是,在GetTimeStamp函数中,我必须将timestamp的秒值转换为纳秒。但由于timeStampDifference是一个sint32参数,它只能保存范围-2147483647至+ 2147483647。在将秒转换为纳秒后,纳秒只能在上述范围内。

所以我正在打印“如果TimeStamp值超出该值,则无法表示,因为它溢出”。但我没有得到预期的产出。

为函数GetTimeStamp编写的逻辑是否正确?有哪些方法可以改善GetTimeStamp函数的功能。

我根据评论编辑了这个问题。热心帮助任何人,我对此有很大的兴趣。

(因为1秒等于1e + 9纳秒,这意味着最大秒值可以是2.147483647秒。我根本不会考虑secondsUp,因为1秒Up等于4294967296秒)

1 个答案:

答案 0 :(得分:0)

问题归结为seconds*1000000000 + ns并且会溢出吗?

#define NS_PER_SEC 1000000000 

int64_t sum_s_ns(int64_t s, int64_t ns) {
  if (s > INT64_MAX/NS_PER_SEC || s < INT64_MIN/NS_PER_SEC) {
    fail_overflow();
    return 0;
  } 
  s *= NS_PER_SEC;
  if (s < 0) {
    // if s + ns < min
    if (ns < INT64_MIN - s) {
      fail_overflow();
      return 0;
    } 
  } else {
    // if s + ns > max
    if (ns > INT64_MAX - s) {
      fail_overflow();
      return 0;
    } 
  }
  return s + ns;
}

请参阅Test if arithmetic operation will cause undefined behavior