Home Ask Login Register

Developers Planet

Your answer is one click away!

TrueSlawter February 2016

If statement 'not working' despite conditions being true

currently going through a bin file full of hex data to process, however currently a match I'm using to try and find a group of 3 hex bytes in the file aren't working correctly. The values are identical however it is not printing my string I've currently got set to confirm that its a match, at present I'm trying to just match the first 3 bytes so we know it works etc. the code is as follows:

match1 = "\\x00\\n\\x00"
print ("match1 ="+match1)

if byteData == match1:
    print ("Byte string 030791 found!")
elif byteData == match1:
    print ("Byte string 050791 found!")

The value of byteData is currently '\x00\n\x00' however the script ignores this and just moves to the exit statement. The file is being opened as follows :

file = open('file.bin', 'rb')
while True:
byte = file.read(3)

When printing the value of byte it reports as "\x00\n\x00" does anyone have any ideas as to why the match isn't working properly?


Martín Muñoz del R&# February 2016


>>> match1 = "\\x00\\n\\x00"
>>> byteData = '\x00\n\x00'
>>> byteData == match1

They are different.

Martijn Pieters February 2016

match1 does not contain 3 bytes. It contains 10:

>>> match1 = "\\x00\\n\\x00"
>>> len(match1)

You escaped the escape sequences, so \\x00 is four bytes, the \ backslash, then the letter x followed by two 0 digits.

Remove the backslash escapes:

match1 = "\x00\n\x00"

Don't try to print this directly; terminals generally won't make nulls visible, so you just get an extra newline. Use the repr() function to produce debug output that looks just like a Python string so you can reproduce that value in your code or the interactive interpreter:

print ("match1 =", repr(match1))

This is also how the interactive interpreter shows you expression results (unless they produced None):

>>> match1 = "\x00\n\x00"
>>> len(match1)
>>> match1
>>> print("match1 =", repr(match1))
match1 = '\x00\n\x00'

Next, if you are using Python 3, you'll still won't have a match because you opened the file in binary mode and are thus getting bytes objects, but your match1 variable is a str text sequence. If you want the two types to match you'll either have to convert (encode the text or decode the bytes), or make match1 a bytes object to start with:

match1 = b'\x00\n\x00'

The b prefix makes that a bytes literal.

Post Status

Asked in February 2016
Viewed 2,829 times
Voted 10
Answered 2 times


Leave an answer

Quote of the day: live life