Question

I am running into problems with Hex values and python. I am trying to write a function which performs a bytewise XOR and returns a Hex value.

Basically I am trying to convert this C# code to Python:

private byte[] AddParity(string _in)
{
byte parity = 0x7f;
List<byte> _out = new List<byte>();
ASCIIEncoding asc = new ASCIIEncoding();

byte[] bytes = asc.GetBytes(_in + '\r');
foreach (byte bt in bytes)
    {
    parity ^= bt;
    _out.Add(bt);
    }
_out.Add(parity);
return _out.ToArray();
}

Can someone point me in the right direction?

Was it helpful?

Solution

parity = 0x7f
parities = [int(item,16) ^ parity for item in "4e 7f 2b".split()]
#or maybe
parities = [ord(item) ^ parity for item in "somestring"]

I guess you are using this as some sort of checksum

parity = 0x7f
bits = []
for bit in "somestring":
    parity ^= ord(bit)
    parity &= 0xFF #ensure width
    bits.append(bit)
bits.append(parity)

to do the checksum more pythonically you could do


this is the answer you want

bytestring = "vTest\r"
bits = chr(0x7f) + bytestring
checksum = reduce(lambda x,y:chr((ord(x)^ord(y))&0xff),bits)
message = bytestring+checksum
print map(lambda x:hex(ord(x)),message)
#Result:['0x76', '0x54', '0x65', '0x73', '0x74', '0xd', '0x32']
# ser.write(message)

if you want to see the hex values

print map(hex,parities)

or to see the binary

print map(bin,parities)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top