Ali Raza Ali Raza - 1 year ago 68
PHP Question

Time encoded in PHP using Bitwise operators. How do I decode a Result?

Time encoded in PHP using Bitwise Or (inclusive or) and Shift left [<<] operator. How do I decode a Result to get Back Year, TotalDays, totalSeconds?


$Year=17; // means 2017
$TotalDays=223;
$totalSeconds=5435;

$Result = ( (intval($Year) << 26) | (intval($TotalDays) << 17) | intval($totalSeconds));


The orignal Algorithm that is encoding hermes time is given below
The orignal Algorithm that is encoding hermes time is given below

unsigned int Gps_DateTimeEncode(short Hours,short Minutes,short Seconds,short Year,short Month, short Days)
{
unsigned int Result;
int Months[12]= {31,28,31,30,31,30,31,31,30,31,30,31};
int TotalSeconds = (Hours *3600) + (Minutes * 60) + Seconds;
int TotalDays=0,i;
if(Year%4==0)
Months[1]=29;

for(i=0;i<Month-1;i++)
{
TotalDays+=Months[i];
}
TotalDays+=Days;
Result = ((Year) << 26) | (TotalDays << 17) | (TotalSeconds) ;
return Result;
}

Answer Source
/**
 * Takes an encoded date and returns a \stdClass object with 'year', 'days'
 * and 'seconds' properties decoded
 * @param int $encoded Encoded date
 * @return \stdClass
 */
function decodeHermesTime($encoded){

    $obj = new \stdClass();

    // right-shift 26 spots to get raw year
    $obj->year = $encoded >> 26;

    // subtract year bits from $encoded to get daysAndSecondsBits
    $daysAndSecondsBits = $encoded - ($obj->year << 26);

    // right-shift 17 times to get days
    $obj->days = $daysAndSecondsBits >> 17;

    // subtract days bits from $daysAndSecondsBits to have raw seconds
    $obj->seconds = $daysAndSecondsBits - ($obj->days << 17);

    return $obj;
}

// usage:
$Result = 17 << 26 | 223 << 17 | 5435;
$r = decodeHermesTime($Result);
echo "Year: $r->year, Days: $r->days, Seconds: $r->seconds";
// Year: 17, Days: 223, Seconds: 5435

Live Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download