Search code examples
pythonbitwise-or

Unsupported operand types for bitwise exclusive OR in Python


I am working with a function which generates cyclical redundancy check values. on data packets prior to sending them out over serial and I seem to be having some problems with the Python not being able to determine the difference between a hex representation and an ascii representation of a value. I send the following data:

('+', ' ', 'N', '\x00', '\x08')

To the following function

# Computes CRC checksum using CRC-32 polynomial 
def crc_stm32(self,data):
    crc = 0xFFFFFFFF
    for d in data:
        crc ^= d
        for i in range(32):
            if crc & 0x80000000:
                crc = (crc << 1) ^ 0x04C11DB7 #Polynomial used in STM32
            else:
                crc = (crc << 1)
    crc = (crc & 0xFFFFFFFF)
    return crc

Now the actual value of the '+' char that is going through this function is (as one might expect) 0x2B, however when Python gets to the line

crc ^= d

I am faced with the following error

unsupported operand type(s) for ^=: 'long' and 'str'

I have tried casting the value to chr(), hex(), int(), long() etc. all to no avail. It seems as though Python is interpreting the '+' value as a char or string.


Solution

  • As per juanpa's comment, the following modification to the code allowed for the proper handling of the data.

        # Computes CRC checksum using CRC-32 polynomial 
    def crc_stm32(self,data):
        crc = 0xFFFFFFFF
        for d in map(ord,data):
            crc ^= d
            for i in range(32):
                if crc & 0x80000000:
                    crc = (crc << 1) ^ 0x04C11DB7 #Polynomial used in STM32
                else:
                    crc = (crc << 1)
        crc = (crc & 0xFFFFFFFF)
        print crc
        return crc