1

I need to increment the hex value (CMD = "\xA0\x00\x00") by 32 in order to write to an i2c eeprom from a python script. I can't figure out how to increment this string in a loop.

I tried to implement it like this

increment =20
CMD = "\xA0\x00\x00" 

for i in range(0,N):
    command=CMD+str(increment)
    increment+=20
    #Code to write to the value goes here

I assumed it would increment in the order

"\xA0\x00\x00"
"\xA0\x00\x0020"
"\xA0\x00\x0040"
"\xA0\x00\x0060"   
#onwards

But it didn't work. Any help would be appreciated!

EDIT :

This is what the output was when i tried to add str(20) to the command.

>>> WCMD = "\xA0\x00\x00"
>>> WCMD=WCMD+str(20)
>>> WCMD
'\xa0\x00\x0020'
>>> 
>>> print(WCMD)
�20
>>> WCMD[0]
'\xa0'
>>> WCMD[1]
'\x00'
>>> WCMD[3]
'2'
>>> WCMD[4]
'0'
>>> WCMD
'\xa0\x00\x0020'
>>> 
  • 1
    What exactly didn't work? What output did you get? Or did you get an error? – JGut Feb 16 '17 at 05:17
  • 1
    @JGut, I edited the question to include some output. When i try to write '\xa0\x00\x00' or '\xa0\x00\x20' or '\xa0\x00\x40', the code works fine, but writing '\xa0\x00\x00' +str(20)' doesn't give errors but doesn't work either. I don't understand how to corectly increment the value – prakash shekhar Feb 16 '17 at 05:28
  • 1
    If you're trying to increase the last character of the string, the cleanest way I think is to use an array of ints, change its content, and then [convert to string](http://stackoverflow.com/questions/3470398/list-of-integers-into-string-byte-array-python) when needed – yeputons Feb 16 '17 at 05:29
  • 1
    @yeputons, the converting an int to a string and appending it to the original string doesn't seem to work. 'x00' is considered as a single character in the string. but on adding a integer to the string, say 20 , the 2 and 0 are considered as separate characters. – prakash shekhar Feb 16 '17 at 05:33
  • 1
    All these `x00`s are processed when Python reads your source file, they do not exist in runtime, so `"\x00" + "01"` is not the same as `"\x0001"`. I suggested using an array `[0,0,0]` to store required codes as `int`s, then modify the array (into `[0,0,32]`) and then converting to array to string when necessary. Does that make sense? – yeputons Feb 16 '17 at 05:36
  • @yeputons, it does, I will go and try that out. Thanks – prakash shekhar Feb 16 '17 at 05:39
  • Need using `binascii` or `struct` module , you can't play `HEX` values directly. String loosing byte index after string operations. – dsgdfg Feb 16 '17 at 06:21

0 Answers0