0

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?

5
  • 4
    Depends. Is the expected result 8192 or 32? Commented Jan 31, 2014 at 9:57
  • @Carsten 32 is the expected result. Commented Jan 31, 2014 at 9:59
  • 1
    Answer below changed accordingly Commented Jan 31, 2014 at 9:59
  • 1
    is it really [0x20, 0x00] or ["0x20", "0x00"] Commented Jan 31, 2014 at 10:00
  • 1
    No there hexadecimal numbers in my list not strings. Commented Jan 31, 2014 at 10:06

2 Answers 2

6

If your input is [0x20, 0x00], then you can do (arr[1]<<8)|arr[0].

If your input is ["0x20", "0x00"], then you can do int(arr[1],16)<<8)|int(arr[0],16).

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

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.

Ask question

Explore related questions

See similar questions with these tags.