Issue
I receive a 32-bit number over the serial line, using num = ser.read(4)
. Checking the value of num
in the shell returns something like a very unreadable b'\xcbu,\x0c'
.
I can check against the ASCII table to find the values of "u" and ",", and determine that the hex value of the received number is actually equal to "cb 75 2c 0c", or in the format that Python outputs, it's b'\xcb\x75\x2c\x0c'
. I can also type the value into a calculator and convert it to decimal (or run int(0xcb752c0c)
in Python), which returns 3413453836.
How can I do this conversion from a binary string literal to an integer in Python?
Solution
Starting from Python 3.2, you can use int.from_bytes
.
Second argument, byteorder, specifies endianness of your bytestring. It can be either 'big' or 'little'. You can also use sys.byteorder to get your host machine's native byteorder.
>>> import sys
>>> int.from_bytes(b'\x11', byteorder=sys.byteorder)
17
>>> bin(int.from_bytes(b'\x11', byteorder=sys.byteorder))
'0b10001'
i've checked the struct module, in the answer below and it apparently support only bytes of a lenght of 2
>>> import struct
>>> print(struct.unpack("h","\x11"))
struct.error: unpack requires a bytes object of length 2
Answered By - XxJames07-
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.