This is a copy of a posting I made on SO, it was suggested I post it here all I've changed from that post is I'm now doing the bitwise AND using a decimal number rather than using bindec("111") to create the mask. The output is identical.
I have a 32 bit number represented as a HEX string that I need to convert to a timestamp following these rules:
What I want to check is that I'm not doing something glaringly stupid? Does my conversion look sane given the timestamp specification?
I've put together the following code to do this. I know PHP isn't the best for this sort of work but it's part of a larger legacy application all written in PHP.
$t is taken from an XML file of readings, one every 5 mins.
// convert the hex string to a string representation of the binary number // sprintf pads leading zeros, for debugging only $binStr = sprintf('%032s', base_convert($t, 16, 2)); //get a decimal representation so we can use the bitwise operator on it $decimal = base_convert($t, 16, 10); // get the first 6 bits $min = $decimal & 63; // 111111 in binary // drop the first 8 bits then apply a mask to the next 5 $hour = ($decimal >> 8) & 31; // 11111 in binary // drop the first 15 bits then apply a mask to the next 1 $daylightSaving = ($decimal >> 15) & 1; // etc $day = ($decimal >> 16) & 31; // 11111 $yearLsb = ($decimal >> 21) & 7; //111 $month = ($decimal >> 24) & 15; //1111 $yearMsb = ($decimal >> 28) & 15; //1111 Logger::debug( "Incoming timestamp " . $t . " \n" . " (as binary " . $binStr . ") converted to: \n" . " Day: " . $day . "\n" . " Month: " . $month . "\n" . " Year: " . $yearMsb . $yearLsb . "\n" . " Hour: " . $hour . "\n" . " Min: " . $min . "\n" . " Daylight saving: ". $daylightSaving );
The output for the last entry in the file is:
Incoming timestamp 2DAC1B0A (as binary 00101101101011000001101100001010) converted to Day: 12 Month: 13 Year: 25 Hour: 27 Min: 10 Daylight saving: 0
I know the file was created at 11:25am on the 12th Nov 2013, the readings are for 11:10 to 11:25 with the last one in the file being the 11:10am one.
The mins match those in the file I get 10 through 25 in 5 min increments. The day is also accurate if I run it against other files.
There's a chance that the equipment manufacturer who wants us to purchase some expensive software to do this parsing has munged the timetamp specification but that being an option I've played with lots of possible combinations in that 32bit integer and I can't see how I can get all the numbers I require from the supplied timestamps.