473,761 Members | 2,293 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to Read Bytes from a file

It seems like this would be easy but I'm drawing a blank.

What I want to do is be able to open any file in binary mode, and read
in one byte (8 bits) at a time and then count the number of 1 bits in
that byte.

I got as far as this but it is giving me strings and I'm not sure how
to accurately get to the byte/bit level.

f1=file('somefi le','rb')
while 1:
abyte=f1.read(1 )

Thanks in advance for any help.

-Greg

Mar 1 '07 #1
18 9179
gr********@gmai l.com <gr********@gma il.comwrote:
It seems like this would be easy but I'm drawing a blank.

What I want to do is be able to open any file in binary mode, and read
in one byte (8 bits) at a time and then count the number of 1 bits in
that byte.

I got as far as this but it is giving me strings and I'm not sure how
to accurately get to the byte/bit level.

f1=file('somefi le','rb')
while 1:
abyte=f1.read(1 )
You should probaby prepare before the loop a mapping from char to number
of 1 bits in that char:

m = {}
for c in range(256):
m[c] = countones(c)

and then sum up the values of m[abyte] into a running total (break from
the loop when 'not abyte', i.e. you're reading 0 bytes even though
asking for 1 -- that tells you the fine is finished, remember to close
it).

A trivial way to do the countones function:

def countones(x):
assert x>=0
c = 0
while x:
c += (x&1)
x >>= 1
return c

you just don't want to call it too often, whence the previous advice to
call it just 256 times to prep a mapping.

If you download and install gmpy you can use gmpy.popcount as a fast
implementation of countones:-).
Alex
Mar 1 '07 #2
Alex Martelli wrote:
You should probaby prepare before the loop a mapping from char to number
of 1 bits in that char:

m = {}
for c in range(256):
m[c] = countones(c)
Wouldn't a list be more efficient?

m = [countones(c) for c in xrange(256)]
Mar 1 '07 #3
On Mar 1, 7:52 am, "gregpin...@gma il.com" <gregpin...@gma il.com>
wrote:
It seems like this would be easy but I'm drawing a blank.

What I want to do is be able to open any file in binary mode, and read
in one byte (8 bits) at a time and then count the number of 1 bits in
that byte.

I got as far as this but it is giving me strings and I'm not sure how
to accurately get to the byte/bit level.

f1=file('somefi le','rb')
while 1:
abyte=f1.read(1 )
import struct
buf = open('somefile' ,'rb').read()
count1 = lambda x: (x&1)+(x&2>0)+( x&4>0)+(x&8>0)+ (x&16>0)+(x&32> 0)+
(x&64>0)+(x&128 >0)
byteOnes = map(count1,stru ct.unpack('B'*l en(buf),buf))

byteOnes[n] is number is number of ones in byte n.

Mar 1 '07 #4
Bart Ogryczak kirjoitti:
On Mar 1, 7:52 am, "gregpin...@gma il.com" <gregpin...@gma il.com>
wrote:
>It seems like this would be easy but I'm drawing a blank.

What I want to do is be able to open any file in binary mode, and read
in one byte (8 bits) at a time and then count the number of 1 bits in
that byte.

I got as far as this but it is giving me strings and I'm not sure how
to accurately get to the byte/bit level.

f1=file('somef ile','rb')
while 1:
abyte=f1.read(1 )

import struct
buf = open('somefile' ,'rb').read()
count1 = lambda x: (x&1)+(x&2>0)+( x&4>0)+(x&8>0)+ (x&16>0)+(x&32> 0)+
(x&64>0)+(x&128 >0)
byteOnes = map(count1,stru ct.unpack('B'*l en(buf),buf))

byteOnes[n] is number is number of ones in byte n.
I guess struct.unpack is not necessary, because:

byteOnes2 = map(count1, (ord(ch) for ch in buf))

seems to do the trick also.

Cheers,
Jussi
Mar 1 '07 #5
Leif K-Brooks <eu*****@ecritt ers.bizwrote:
Alex Martelli wrote:
You should probaby prepare before the loop a mapping from char to number
of 1 bits in that char:

m = {}
for c in range(256):
m[c] = countones(c)

Wouldn't a list be more efficient?

m = [countones(c) for c in xrange(256)]
Yes, or an array.array -- actually I meant to use m[chr(c)] above (so
you could use the character you're reading directly to index m, rather
than calling ord(byte) a bazillion times for each byte you're reading),
but if you're using the numbers (as I did before) a list or array is
better.
Alex
Mar 1 '07 #6
On Mar 1, 8:53 am, "Bart Ogryczak" <B.Ogryc...@gma il.comwrote:
On Mar 1, 7:52 am, "gregpin...@gma il.com" <gregpin...@gma il.com>
wrote:
It seems like this would be easy but I'm drawing a blank.
What I want to do is be able to open any file in binary mode, and read
in one byte (8 bits) at a time and then count the number of 1 bits in
that byte.
I got as far as this but it is giving me strings and I'm not sure how
to accurately get to the byte/bit level.
f1=file('somefi le','rb')
while 1:
abyte=f1.read(1 )

import struct
buf = open('somefile' ,'rb').read()
count1 = lambda x: (x&1)+(x&2>0)+( x&4>0)+(x&8>0)+ (x&16>0)+(x&32> 0)+
(x&64>0)+(x&128 >0)
byteOnes = map(count1,stru ct.unpack('B'*l en(buf),buf))

byteOnes[n] is number is number of ones in byte n.

This solution looks nice, but how does it work? I'm guessing
struct.unpack will provide me with 8 bit bytes (will this work on any
system?)

How does count1 work exactly?

Thanks for the help.

-Greg

Mar 1 '07 #7
On Mar 2, 12:53 am, "Bart Ogryczak" <B.Ogryc...@gma il.comwrote:
>
import struct
buf = open('somefile' ,'rb').read()
count1 = lambda x: (x&1)+(x&2>0)+( x&4>0)+(x&8>0)+ (x&16>0)+(x&32> 0)+
(x&64>0)+(x&128 >0)
byteOnes = map(count1,stru ct.unpack('B'*l en(buf),buf))
byteOnes = map(count1,stru ct.unpack('%dB' %len(buf),buf))

Mar 1 '07 #8
On Mar 1, 4:58 pm, "gregpin...@gma il.com" <gregpin...@gma il.com>
wrote:
On Mar 1, 8:53 am, "Bart Ogryczak" <B.Ogryc...@gma il.comwrote:
On Mar 1, 7:52 am, "gregpin...@gma il.com" <gregpin...@gma il.com>
wrote:
It seems like this would be easy but I'm drawing a blank.
What I want to do is be able to open any file in binary mode, and read
in one byte (8 bits) at a time and then count the number of 1 bits in
that byte.
I got as far as this but it is giving me strings and I'm not sure how
to accurately get to the byte/bit level.
f1=file('somefi le','rb')
while 1:
abyte=f1.read(1 )
import struct
buf = open('somefile' ,'rb').read()
count1 = lambda x: (x&1)+(x&2>0)+( x&4>0)+(x&8>0)+ (x&16>0)+(x&32> 0)+
(x&64>0)+(x&128 >0)
byteOnes = map(count1,stru ct.unpack('B'*l en(buf),buf))
byteOnes[n] is number is number of ones in byte n.

This solution looks nice, but how does it work? I'm guessing
struct.unpack will provide me with 8 bit bytes

unpack with 'B' format gives you int value equivalent to unsigned char
(1 byte).
(will this work on any system?)
Any system with 8-bit bytes, which would mean any system made after
1965. I'm not aware of any Python implementation for UNIVAC, so I
wouldn't worry ;-)
How does count1 work exactly?
1,2,4,8,16,32,6 4,128 in binary are
1,10,100,1000,1 0000,100000,100 0000,10000000
x&1 == 1 if x has first bit set to 1
x&2 == 2, so (x&2>0) == True if x has second bit set to 1
.... and so on.
In the context of int, True is interpreted as 1, False as 0.

Mar 1 '07 #9
On Mar 1, 12:46 pm, "Bart Ogryczak" <B.Ogryc...@gma il.comwrote:
This solution looks nice, but how does it work? I'm guessing
struct.unpack will provide me with 8 bit bytes

unpack with 'B' format gives you int value equivalent to unsigned char
(1 byte).
(will this work on any system?)

Any system with 8-bit bytes, which would mean any system made after
1965. I'm not aware of any Python implementation for UNIVAC, so I
wouldn't worry ;-)
How does count1 work exactly?

1,2,4,8,16,32,6 4,128 in binary are
1,10,100,1000,1 0000,100000,100 0000,10000000
x&1 == 1 if x has first bit set to 1
x&2 == 2, so (x&2>0) == True if x has second bit set to 1
... and so on.
In the context of int, True is interpreted as 1, False as 0.
Thanks Bart. That's perfect. The other suggestion was to precompute
count1 for all possible bytes, I guess that's 0-256, right?

Thanks again everyone for the help.

-Greg

Mar 1 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
7773
by: hunterb | last post by:
I have a file which has no BOM and contains mostly single byte chars. There are numerous double byte chars (Japanese) which appear throughout. I need to take the resulting Unicode and store it in a DB and display it onscreen. No matter which way I open the file, convert it to Unicode/leave it as is or what ever, I see all single bytes ok, but double bytes become 2 seperate single bytes. Surely there is an easy way to convert these mixed...
5
5117
by: Sumana | last post by:
Hi All, We developed our project on VC++.Net console application to create image of disk and to write the image We are having problem with reading and writing the sector beyond 6GB Disk or Partition we are using ReadFile , WriteFile and setFilePointerEx to read and write the sectors and we are reading/writing 102400 sectors together, even we have reduced the sectors still it is not able to read or write, our program is working fine...
35
11490
by: RyanS09 | last post by:
Hello- I am trying to write a snippet which will open a text file with an integer on each line. I would like to read the last integer in the file. I am currently using: file = fopen("f.txt", "r+"); fseek(file, -2, SEEK_END); fscanf(file, "%d", &c); this works fine if the integer is only a single character. When I get into larger numbers though (e.g. 502) it only reads in the 2. Is there
3
4107
by: ramesh | last post by:
can any one help me to solve this one we need to write a c program, Consider a file of size 5000 bytes. Open the file and read to a buffer of size buf; We have to read 1000 bytes only from the file at a time and after displaying the file we have to lseek 500 bytes back in the file And read file from 500 to 1000. we have to read this type upto end of
6
5810
by: =?Utf-8?B?VGhvbWFzWg==?= | last post by:
Hi, Is it possible to read a file in reverse and only get the last 100 bytes in the file without reading the whole file from the begining? I have to get info from files that are in the last 100 bytes of the file and some of these files are 600Mb -1 GB in size. I am getting "outofMemory.." exceptions on the largest files and the other files take "forever" to get the last 100 bytes. This is the code I have currently that works with...
14
11642
by: chance | last post by:
Hello, I have a file on disk called TEMP.ZIP and I would like to somehow get this into a memory stream so I can eventually do this: row = dataStream.ToArray() However, I am not sure of the correct way to get it into a memory stream. Any help appreciated.
6
32919
by: Thomas Kowalski | last post by:
Hi, currently I am reading a huge (about 10-100 MB) text-file line by line using fstreams and getline. I wonder whether there is a faster way to read a file line by line (with std::string line). Is there some way to burst read the whole file and later "extract" each line? Thanks in advance, Thomas Kowalski
2
5453
by: Kevin Ar18 | last post by:
I posted this on the forum, but nobody seems to know the solution: http://python-forum.org/py/viewtopic.php?t=5230 I have a zip file that is several GB in size, and one of the files inside of it is several GB in size. When it comes time to read the 5+GB file from inside the zip file, it fails with the following error: File "...\zipfile.py", line 491, in read bytes = self.fp.read(zinfo.compress_size) OverflowError: long it too large to...
9
3848
by: vineeth | last post by:
Hello all, I have come across a weird problem, I need to determine the amount of bytes read from a file, but couldn't figure it out , My program does this : __ file = open("somefile") data = file.read() print "bytes read ", len(data) ---
4
4255
by: skunapareddy | last post by:
I am needing to read a blob from database and pass it to another java program. I researched internet and found a program that reads a file on the client pc and gives bytes, but when I modified the code to read a blob from DB I am not having any luck, I am running this java programs using JDEVELOPER. Can anyone please give me some help? The code is as follows: ... private static byte getBytesFromBlob(Blob blob) throws Exception { ...
0
10136
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9989
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9811
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8814
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6640
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3913
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3509
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2788
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.