Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

bitwise operators - Python bitand (&) vs and

Hi all I have this part of code:

for line in response.body.split("
"):
    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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...