Convert 8 Byte timestamp to a human readable time!

21 views (last 30 days)
I created a Matlab script that reads a file and parses out data. One data field is 8 bytes and represents a timestamp in seconds.
I browsed around and asked a few questions and came up with the following code for reading the eight bytes and converting to a time in seconds: ("this_timestamp" is the full 8 bytes of time data, file is little-endian format)
message_timestamp = typecast(uint64(hex2dec([reshape(flipud(rot90(dec2hex(this_timestamp(8:-1:5)))),1,[]),reshape(flipud(rot90(dec2hex(this_timestamp(4:-1:1)))),1,[])])),'double');
This seems to work fine under most situations, (I get the times exactly as I know they should be), but in rare circumstances the times come out as "e-310". One case this happens in is when the 8 bytes are: "00 00 00 00 00 00 5d 40" which after converting should be 116.000000.
Is there something I'm doing (or not doing) that doesn't handle data with "0"s after the decimal?

Accepted Answer

James Tursa
James Tursa on 23 Sep 2015
Edited: James Tursa on 23 Sep 2015
I haven't gone through your one-liner in any detail, but if you are starting with the 8 bytes shown above, then a simple typecast seems to work on my PC (little endian):
>> h = ['00';'00';'00';'00';'00';'00';'5d';'40'] % the hex values
h =
00
00
00
00
00
00
5d
40
>> this_timestamp = uint8(hex2dec(h)) % the equivalent 8 bytes
this_timestamp =
0
0
0
0
0
0
93
64
>> typecast(this_timestamp,'double')
ans =
116
  2 Comments
Art
Art on 24 Sep 2015
Ahh! Although by accident, you pointed me in the right direction --> I am using dec2hex to create a single field of hex values that should be 8 digits long (4bytes). I needed to add ",2" to my dec2hex conversions to make sure every hex byte was 2 digits long. Otherwise the field was < 8 digits, missing some important zeros, and read as the wrong dec number. Should be:
message_timestamp = typecast(uint64(hex2dec([reshape(flipud(rot90(dec2hex(this_timestamp(8:-1:5) *,2*))),1,[]),reshape(flipud(rot90(dec2hex(this_timestamp(4:-1:1) *,2*))),1,[])])),'double');
Art
Art on 26 Sep 2015
Also, thanks for pointing me to the much simpler solution. I was going through two steps too many. I was converting my dec to hex, and then back to dec when all I had to do was:
message_timestamp = typecast(uint8(this_timestamp(1:1:8)),'double');

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!