0

I am using python as the main scripting language on a micro controller. The micro controller reads two 8-bit hex numbers from the I2C bus; for example:

out_L = C2
out_H = F2

Both these are received as strings in python. F2C2 represents a two's complement number. I need the decimal value of the number.

I can convert the hex strings to binary strings with

bin_out = "0b" + ( bin(int(hex_out, 16))[2:] ).zfill(8)

Now I have to convert the binary value to a decimal value which is where I am stuck. I first have to do two's complement convertion and then convert to decimal. Because the binary value is still a string I can't do normal binary operations on it and can't convert it to decimal. Please assist. All my efforts to correctly change the binary string to binary value provides me with the incorrect value.

2 Answers 2

1

You may just apply the 2's compliment directly to the original int value:

out_L = "C2"
out_H = "F2"

hex_out = ''.join((out_H, out_L))
value = int(hex_out, 16) # value = 62146
if value> 0x7FFF:
    value -= 0x10000

print value # output -3390
Sign up to request clarification or add additional context in comments.

Comments

0

Convert binary to decimal in python by using:

int(binary_number,2)

1 Comment

This also works - I somehow could not get it working earlier.

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.