使用按位运算符在 PHP 中编码的时间.如何解码结果?



在PHP中使用Bitwise Or(包含or(和Shift left [<<]运算符进行时间编码。如何解码结果以返回年份、总天数、总秒数?

$Year=17;   // means 2017
$TotalDays=223;
$totalSeconds=5435;
$Result = ( (intval($Year) << 26) | (intval($TotalDays) << 17) | intval($totalSeconds));

下面给出了编码爱马仕时间的原始算法 下面给出了编码爱马仕时间的原始算法

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;                                                    
}
/**
* 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

现场演示

最新更新