syncMaster for problem 3

hdtimeval_math.cpp

Committer:
the729
Date:
2010-12-03
Revision:
0:b9f06a7ae791

File content as of revision 0:b9f06a7ae791:

#include "hdtimeval_math.h"

void hdtv_add (hdtimeval_t * r, hdtimeval_t * v1, hdtimeval_t * v2)
{
    r->tv_sec = v1->tv_sec + v2->tv_sec;
    r->ticks = v1->ticks + v2->ticks;
    if (r->ticks >= MAX_TICK) {
        r->tv_sec++;
        r->ticks -= MAX_TICK;
    }
}

void hdtv_div2 (hdtimeval_t * r, hdtimeval_t * v)
{
    if (v->tv_sec & 0x1) {
        r->ticks = ((v->ticks+MAX_TICK)>>1);
    } else {
        r->ticks = (v->ticks>>1);
    }
    r->tv_sec = (v->tv_sec>>1);
}

void hdtv_div8 (hdtimeval_t * r, hdtimeval_t * v)
{
    r->ticks = ((v->ticks+MAX_TICK*(v->tv_sec & 0x7))>>3);
    r->tv_sec = (v->tv_sec>>3);
}

void hdtv_sub (hdtimeval_t * r, hdtimeval_t * v1, hdtimeval_t * v2)
{
    r->tv_sec = v1->tv_sec - v2->tv_sec;
    if (v1->ticks < v2->ticks) {
        r->ticks = MAX_TICK + v1->ticks - v2->ticks;
        r->tv_sec --;
    } else {
        r->ticks = v1->ticks - v2->ticks;
    }
}

void hdtv_muldiv (hdtimeval_t * r, hdtimeval_t * v, hdtimeval_t * m, hdtimeval_t * d)
{
    double dblm, dbld, factor, rsec, rticks;
    uint32_t irticks, c;
    int32_t irsec;

    dblm = (double)(m->tv_sec) * (double)MAX_TICK + (double)(m->ticks);
    dbld = (double)(d->tv_sec) * (double)MAX_TICK + (double)(d->ticks);
    factor = dblm / dbld;
    
    rsec = (double)(v->tv_sec) * factor;
    rticks = (double)(v->ticks) * factor + (rsec - floor(rsec)) * (double)MAX_TICK;
    irticks = (uint32_t)rticks;
    irsec = (int32_t)rsec;
    c = irticks / MAX_TICK;
    r->tv_sec = irsec + c;
    r->ticks = irticks - c * MAX_TICK;
}

void hdtv_totv(timeval_t * r, hdtimeval_t * v)
{
    r->tv_sec = v->tv_sec;
    r->tv_usec = (v->ticks + 48)/96;
    if (r->tv_usec >= 1000000) {
        r->tv_sec ++;
        r->tv_usec -= 1000000;
    }
}