Python Forum

Full Version: Read binary from file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have some trouble reading binary file



with open('myfile', 'rb') as fl:
    b = fl.read( 1 )
    for x in range( 0,4):
         tuppleCounter[ ( ( 3 << ( x * 2 ) ) & b ) >> ( x*2 ) ]+=1
The interpreter says
TypeError: unsupported operand type(s) for &: 'int' and 'str'

Also
b = int( fl.read( 1 ), 10 )
and
b = int( fl.read( 1 ) )
for both says
ValueError: invalid literal for int() with base 10: 'i'

i dont know what im doing wrong
Please post entire error traceback verbatim
supple sample file if possible, or where it can be downloaded
b will read 1 byte, starting at byte number 1 in file
You don't show tuppleCounter
is this what you wanted?

You don't need to supply number base to int if decimal
If I try with random binary file:
>>> with open('image_002.jpg', 'rb') as fp:
...     b = fp.read(1)
... 
>>> b
b'\xff'
>>> for x in range( 0,4):
...     tuppleCounter[ ( ( 3 << ( x * 2 ) ) & b ) >> ( x*2 ) ]+=1
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'tuppleCounter' is not defined
if __name__ == "__main__":

    tuppleCounter = [ 0, 0, 0 ,0 ]

    with open('myfile', 'rb') as fl:
        b = fl.read( 1 )

        for x in range( 0,4):
            tuppleCounter[ ( ( 3 << ( x * 2 ) ) & b ) >> ( x*2 ) ]+=1

    print tuppleCounter;

nextor@leon:~/Projects/tmp/pypress$ python test.py
Traceback (most recent call last):
File "test.py", line 10, in <module>
tuppleCounter[ ( ( 3 << ( x * 2 ) ) & b ) >> ( x*2 ) ]+=1
TypeError: unsupported operand type(s) for &: 'int' and 'str'
nextor@leon:~/Projects/tmp/pypress$
Are you using PYTHON 2 ?????
(Nov-27-2018, 08:45 PM)Gribouillis Wrote: [ -> ]Are you using PYTHON 2 ?????
it says Python 2.7.15+
And with Python 3.6.7rc1 it says the same
Python 2 is almost dead (still supported during one year), you should be using python 3.5 or 3.6 or 3.7.
You need to convert the char you read to an int. In python 2, do
b = fl.read(1)
b = ord(b)
In python 3, use
b = fl.read(1)
b = b[0]
It works, Thanks Gribouillis