简体   繁体   中英

manipulating a hex string for i2c in Python

I am using i2c and Python 2.7. I have a hex string that looks like this:

'\x80\x0A\x01\x0B\x99\x0C\x04\x0D\xCC'  

(write address, register, value, register, value, register, value, register, value)

I need to change the value of \\x04 and \\xCC with the first two and last two characters of a decimal converted to a hex.

a = 857
a = hex(a)
a
'0x359'
a = a[2:]
a
'359'
a = a.zfill(4)
a
'0359'
high = a[:2]
high
'03'
low = a[2:]
low
'59'

\\x03 needs to go in the \\xCC spot and \\x59 needs to go in the \\x04 spot.

The string needs to look like this:

'\x80\x0A\x01\x0B\x99\x0C\x59\x0D\x03'

My first problem is getting the string to act like a string. If I use 'r' in front of the string and then use str.replace() , the resulting string gives me:

'\\x80\\x0A\\x01\\x0B\\x99\\x0C\\x59\\x0D\\x03'

and my device does not respond to it.

If I don't use the 'r', I get:

ValueError: invalid \\x escape

when I try to make the string a variable.

I've tried a straight concatenation:

a = '\x80\x0A\x01\x0B\x99\x0C' + '\x' + low + '\x0D' + '\x' + high

ValueError: invalid \\x escape

or

a = '\x80\x0A\x01\x0B\x99\x0C' + r'\x' + low + r'\x0D' + r'\x' + high
a
'\x80\n\x01\x0b\x99\x0c\\x59\\x0D\\x03' (device does not respond)

or

a = '\x80\x0A\x01\x0B\x99\x0C\x' + low + '\x0D\x' + high

ValueError: invalid \\x escape

To work on these "strings" as byte arrays, try bytearray like:

Code:

data = [int(x) for x in bytearray('\x80\x0A\x01\x0B\x99\x0C\x04\x0D\xCC')]
want = [int(x) for x in bytearray('\x80\x0A\x01\x0B\x99\x0C\x59\x0D\x03')]

num = 857
high, low = int(num / 256), num % 256

new_data = list(data)
new_data[data.index(int('cc', 16))] = high
new_data[data.index(int('04', 16))] = low

assert want == new_data

# convert back to string
result = ''.join(chr(d) for d in data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM