I need to read time data from sensor. Here are the instructions from manual:
I have written code in Python, but I feel like there should be some better way:
# 1
data_bytes = b'\x43\x32\x21\x10'
print('data_bytes: ', data_bytes, len(data_bytes)) # why it changes b'\x43\x32\x21\x10' to b'C2!\x10' ???
# 2
data_binary = bin(int.from_bytes(data_bytes, 'little')) # remove '0b' from string
print('data_binary: ', data_binary, len(data_binary))
data_binary = data_binary[2:]
print('data_binary: ', data_binary, len(data_binary)) # should be: 0001 0000 0010 0001 0011 0010 0100 0011, 32
# 3
sec = data_binary[0:-20]
print(sec, len(sec)) # should be: 0001 0000 0010, 12
sec = int(sec, 2)
print(sec)
usec = data_binary[-20:]
print(usec, len(usec)) # 0001 0011 0010 0100 0011, 20
usec = int(usec, 2)
print(usec)
# 4
print('time: ', sec + usec/1000000) # should be: 258.078403
Results:
data_bytes: b'C2!\x10' 4
data_binary: 0b10000001000010011001001000011 31
data_binary: 10000001000010011001001000011 29
100000010 9
258
00010011001001000011 20
78403
time: 258.078403
I have questions:
- Why Python changes b'\x43\x32\x21\x10' to b'C2!\x10'?
- Why is the length of the message 29 bits and not 32?
- Is it possible to do this in better/cleaner/faster way?
Thanks!