mardi 22 août 2017

Conversion of seconds to nanoseconds in timestamp and represent using signed integer

Here is my code:

#include<stdio.h>

typedef unsigned int uint32;
typedef unsigned short int uint16;

typedef signed short int sint16;

#define MAX_NS 999999999
#define MAX_S  4294967295

typedef struct
{
   uint32 nanoseconds;  
   uint32 seconds;
   uint16 secondsUp;  
}TimeStampType;

TimeStampType timeStamp[3];
sint16 timeStampDifference;

 void GetTimeStamp(sint16* timeStampDifference,int ID)
{
        /* 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[ID].secondsUp > 0)||(timeStamp[ID].seconds > 3)

||((timeStamp[ID].seconds == 2)&&(timeStamp[ID].nanoseconds > 147483647))){

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

    else{

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

}

 void SetTimeStamp(int ID)
{
    if(ID == 0){
        timeStamp[0].nanoseconds =  2900 ;
        timeStamp[0].seconds =  4 ;
        timeStamp[0].secondsUp = 0 ;
    }

    else if(ID == 1){
        timeStamp[1].nanoseconds =  MAX_NS ;
        timeStamp[1].seconds =  2 ;
        timeStamp[1].secondsUp = 0 ;
    }   

    else{
        timeStamp[2].nanoseconds =  10 ;
        timeStamp[2].seconds =  2 ;
        timeStamp[2].secondsUp = 0 ;
    }

}


int main()
{

    SetTimeStamp(0);
    SetTimeStamp(1);
    SetTimeStamp(2);

    GetTimeStamp(&timeStampDifference,0);
    printf("%d\n",timeStampDifference);
    timeStampDifference=0;

    GetTimeStamp(&timeStampDifference,1);
    printf("%d\n",timeStampDifference);
    timeStampDifference=0;

    GetTimeStamp(&timeStampDifference,2);
    printf("%d\n",timeStampDifference);
    timeStampDifference=0;

     return 0;

}

What I am trying to do is, I have to convert seconds value of timestamp to nanoseconds.But since timeStampDifference is a sint32 parameter,it can hold only the values in the range -2147483647 to +2147483647.So nanoseconds can only be in the mentioned range after converting seconds to nanseconds.

So I am printing "TimeStamp value can not be represented since it overflows" if it exceeds the value. But I am not getting expected output.

Is the Logic written for function GetTimeStamp correct?What are the ways to improve the functionality of GetTimeStamp function.KIndly help.

(Since 1 second equals 1e+9 nanoseconds,which means the max seconds value can be 2.147483647 seconds.I will not consider secondsUp at all ,since 1 secondsUp equals 4294967296 seconds)

Aucun commentaire:

Enregistrer un commentaire