1

I am retrieving bytes of data from an IC2 device using the read_i2c_block_data function. Within this block of data are signed 16-bit values that I want to display. I am able to print out the value correctly using the following:

print ("PC12  : %d mW" % int.from_bytes((return_data[5],return_data[6]), byteorder='little', signed=True))

Though, I have been trying print out the value using the following, which doesn't work and I don't know why. I am curious to why I can't get it to work.

print ("PC12  : %d mW" % int.from_bytes(return_data[5:6], byteorder='little', signed=True))

Does anyone know what I am doing wrong? I thought I could specify the range in the from_bytes function.

Thanks, Mark

2
  • 1
    What exactly happens, and how does that differ from what you expected to happen? What type is return_data? Commented May 1, 2015 at 3:38
  • The conversion was not correct and only converting just one of the bytes, but I couldn't figure out why. vituat enlightened me to what was happening. Commented May 1, 2015 at 3:56

1 Answer 1

2

return_data[5:6] returns an array consisting of a single element at index 5:

>>> return_data = b'\00\01\02\03\04\05\06'
>>> return_data[5:6]
b'\x05'

Since you want to convert a 16-bit integer, you need to use return_data[5:7].

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

1 Comment

vitaut, brilliant. That worked like a charm. It appears I really didn't understand the indexing/range syntax. With that, I was able to get the selection to work and fix a few other bugs I had. Thanks!!!!

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.