Given these 2 numbers (milliseconds since Unix epoch), 1656773855233 and 1656773888716, I'm trying to write them to a binary object. The kicker is that I want to write them to a 11 byte object.
If I accept that the timestamps can only represent dates before September 7th 2039, the numbers should each fit within 41bits. 2 41bit numbers fits within 88bit (11bytes) with 6 bits in excess.
I've tried the following python code, as a (rather naive) way to achieve this:
receive_time=1656773855233
event_time=1656773888716
with open("test.bin", "wb") as f:
f.write(receive_time.to_bytes(6, "big"))
f.write(event_time.to_bytes(6, "big"))
print(f"{receive_time:08b}")
print(f"{event_time:08b}")
with open("test.bin", "rb") as f:
a = f.read()
print(" ".join(f"{byte:08b}" for byte in a))
The output of the code very clearly shows that the test.bin
file is 12 bytes, because each timestamp is padded with 7 0's when converted to bytes.
How would I go about writing the timestamps to test.bin
without padding them individually?
The end result should be something like 0000001100000011011111101101010110010000000000111000000110111111011010110100101011001100
or 3037ED5900381BF6B4ACC
EDIT: Question originally mentioned that a 41bit number could only represent dates before May 15th, 2109 if that number represented milliseconds since the Unix epoch. That is wrong, as interjay correctly pointed out, a 41bit number would only represent 69,7 years and the max date would thus be September 7th, 2039. A 42bit number, however, can represent a number that represents dates before May 15th, 2109.
CodePudding user response:
Use a bit shift to combine both times into the same int, before converting that to bytes
:
x = (receive_time << 41) event_time
b = x.to_bytes(11, 'big')
with open("test.bin", "wb") as f:
f.write(b)