Search code examples
pythonbitwise-operatorslogical-and

Python bitand (&) vs and


Hi all I have this part of code:

for line in response.body.split("\n"):
    if line != "": 
        opg = int(line.split(" ")[2])
        opc = int(line.split(" ")[3])
        value = int(line.split(" ")[5])
        if opg==160 & opc==129:
            ret['success'] = "valore: %s" % (value)
            self.write(tornado.escape.json_encode(ret))

I have a series of line of type

1362581670        2459546910990453036    156     0     30      0

I want to take only the line where the third and fourth element is respectively 160 and 129. This code doesn't work. Do I have to do some casting? I think opg==160 is working to compare int with int...


Solution

  • You got confused with the operators; and is the correct boolean test, & is a binary bitwise operator instead:

    if opg == 160 and opc == 129:
    

    As a numeric operator, the & operator has a higher precedence than comparison operators, while the boolean operators have a lower precedence. The expression opg == 160 & opc == 129 is thus interpreted as opg == (160 & opc) == 129 instead, which is probably not what you wanted.

    You can simplify your code somewhat:

    for line in response.body.splitlines():
        if line:
            line = map(int, line.split())
            opg, opc, value = line[2], line[3], line[5]
            if opg == 160 and opc == 129:
                ret['success'] = "valore: %s" % (value)
                self.write(tornado.escape.json_encode(ret))