Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
I have an unsigned integer that is 16 bits coming in on the USB, these appear as 2 bytes in my list that is returned, e.g. [0x20, 0x00]. How would I combine these in to a number in python?
[0x20, 0x00]
["0x20", "0x00"]
If your input is [0x20, 0x00], then you can do (arr[1]<<8)|arr[0].
(arr[1]<<8)|arr[0]
If your input is ["0x20", "0x00"], then you can do int(arr[1],16)<<8)|int(arr[0],16).
int(arr[1],16)<<8)|int(arr[0],16)
Add a comment
This also works:
>>> import struct >>> struct.unpack('<H', ''.join(map(chr, [0x20, 0x00])))[0] 32
The struct module is quite generic, it can be used in similar situations, and it becomes convenient as soon as 4-byte or 8-byte integers are needed.
struct
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.
[0x20, 0x00]or["0x20", "0x00"]