0

I need to convert this C code to python.
void GetChkSum(Int len, PSTR buf, PSTR res)
{
memset(res, 0, 4);
for(int i=0; i<len; i+=4)
{
res[0]^=(buf+i)[0];
res[1]^=(buf+i)[1];
res[2]^=(buf+i)[2];
res[3]^=(buf+i)[3];
}
res[0]=~res[0];
res[1]=~res[1];
res[2]=~res[2];
res[3]=~res[3];
}

In my case, buf is bytes object.
for example: buf = b'00000001TXBEG 0000'
len is its length: 18

I've already tried convert it, below is my code. I got this error:
'bytes' object does not support item assignment.

def checkSum(xLen, buff) :
    res = b'0000'
    i = 0
    while(i < xLen) :
        res[0] ^= buff[i]
        res[1] ^= buff[i+1]
        res[2] ^= buff[i+2]
        res[3] ^= buff[i+3]
        i += 4
    res[0] = not res[0]
    res[1] = not res[1]
    res[2] = not res[2]
    res[3] = not res[3]
    return res

Any suggestions appreciated.
Thanks in advance.

1
Contributor
2
Replies
4
Views
6 Years
Discussion Span
Last Post by _neo_
0

I've changed my code with bytearray()

def checkSum(xLen, buff) :
    res = bytearray(b'0000')
    i = 0
    while(i < xLen) :
        res[0] ^= buff[i]
        res[1] ^= buff[i+1]
        res[2] ^= buff[i+2]
        res[3] ^= buff[i+3]
        i += 4
    print(res)
    res[0] = ~res[0]
    res[1] = ~res[1]
    res[2] = ~res[2]
    res[3] = ~res[3]
    print(res)
    return res

When I try this, I got error 'byte must be in range 0-256'

checkSum(20, b'1.00internalSRVM    ')
1

I've solved my problem

def checkSum(buff) :
  '''Make check sum of bytes(buff)'''
  res=bytearray('0000','ascii')
  res[0],res[1],res[2],res[3]=(0x00,0x00,0x00,0x00)
  xLen=len(buff)
  i=0
  while(i < xLen) :
    res[0]=res[0]^buff[i]
    res[1]=res[1]^buff[i+1]
    res[2]=res[2]^buff[i+2]
    res[3]=res[3]^buff[i+3]
    i += 4
  ## x XOR 0xFF inverts least 8 bits
  res[0]=res[0]^0xff
  res[1]=res[1]^0xff
  res[2]=res[2]^0xff
  res[3]=res[3]^0xff
  return res
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.