I am working on a program to decode MMS PDU files. They are binary files and I am reading them byte by byte and decoding each header value as I come to it.
One header value is the Date, and it's represented as follows (in hex):
85 04 57 E2 A2 49
0x85 is the "Date" header,
0x04 is the data length (4 bytes) and the 4 following bytes represent the date (timestamp).
I have code to read those 4 bytes and return it to me as a
\x57 is a
\x49 is an
In order to parse this as a date, I need to convert it to an int. These bytes represent the timestamp
I have code to convert this byte array into an int, but there has got be a better way to do it than the way I came up with.
timestamp = int(''.join(map(hex, byte_range)).replace('0x', ''), 16) value = datetime.fromtimestamp(timestamp)
That is, I am converting every byte to a string (like
"0x57"), joining them together, removing the
"0x"s, then reading that string as a base 16 value. This works, but it seems a little too convoluted.
I then realized that I could replace the
binascii.hexlify, so now my code is:
timestamp = int(binascii.hexlify(byte_range), 16) value = datetime.fromtimestamp(timestamp)
Like I said, this code works, but I just feel there's a better way to do this than to convert the bytearray into a string and then parse that string back as a base-16 int.