Question

I feel like a complete tool for posting this, it is so basic and I cant believe I have wasted the last two days on this problem. I've tried all the solutions I can find on this (seriously, I will show you my internet history) but to no avail. Here is the problem:

I am parsing a serial string in from a uC. It is 52 bytes long and contains a lot of different variables of data. The data in encoded in packed binary coded decimal.

Ex: .....blah.....0x01 0x5E .....blah

015E hex gives 350 decimal. This is the value I want. I am reading in the serial string just fine, I used binascii.hexifiy to print the bytes to ensure it is corrent. I use

data = ser.read()

and placed the data in an array if an newline is not received. I have tried making the array a bytearray, list, anything that I could find, but none work.

I want to send the required two byte section to a defined method.

def makeValue(highbyte, lowbyte)

When I try to use unpack, join, pack, bit manipulation, string concentation, I keep getting the same problem.

Because 0x01 and 0x5E are not valid int numbers (start of heading and ^ in ASCII), it wont work. It wont even let me join the numbers first because it's not a valid int.

using hex(): hex argument can't be converted to hex. Joining the strings: invalid literal for int() with base 16: '\x01^' using int: invalid literal for int() with base 10: '\x01^' Packing a struct: struct.error: cannot convert argument to integer

Seriously, am I missing something really basic here? All the examples I can find make use of all the functions above perfectly but they specificy the hex numbers '0x1234', or the numbers they are converting are actual ASCII numbers. Please help.

EDIT I got it, ch3ka set me on the right track, thanks a million!

I don't know why it wouldn't work before but I hex'ed both values

one = binascii.hexlify(line[7])
two = binascii.hexlify(line[8])
makeValue(one, two)` 

and then used the char makeValues ch3ka defined:

def makeValue(highbyte, lowbyte)
    print int(highbyte, 16)*256 + int(lowbyte, 16)

Thanks again!!!

Was it helpful?

Solution

you are interpreting the values as chars. Feeding chars to int() won't work, you have to feed the values as strings, like so: int("0x5E", 16). What you are attempting is in fact int(chr(int("0x5E", 16)),16), which is int("^",16) and will of course not work.

Do you expect these results?

makevalue('0x01', '0x5E') ->  350 0x15e 0b101011110
makevalue('0xFF', '0x00') ->  65280 0xff00 0b1111111100000000
makevalue('0x01', '0xFF') ->  511 0x1ff 0b111111111
makevalue('0xFF', '0xFF') ->  65535 0xffff 0b1111111111111111

If so, you can use this:

def makeValue(highbyte, lowbyte):
    return int(highbyte, 16)*256 + int(lowbyte, 16)

or the IMO more ugly and errorprone:

def makeValue(highbyte, lowbyte):
    return int(highbyte+lowbyte[2:], 16) # strips leading "0x" from lowbyte be4 concat
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top