I need to count how many bits are set in a binary file. I considered processing the strings from an "od -x" output, since that would remove the many consecutive zero bytes I expect, but I also took a whack with this:
perl -e '$bytes= -s "dwtest.dat";
open(FIN,"dwtest.dat") or die "cant open file\n";
$sum=0;
for($i=0;$i<$bytes;$i++){
read(FIN,$c,1);
(($c | 0x01) && ($sum++));
(($c | 0x02) && ($sum++));
(($c | 0x04) && ($sum++));
(($c | 0x08) && ($sum++));
(($c | 0x10) && ($sum++));
(($c | 0x20) && ($sum++));
(($c | 0x40) && ($sum++));
(($c | 0x80) && ($sum++));
}
print "$sum bits are set\n";'
It works, but it's slow.
Does anyone have a faster solution?
update
pg is right, I'm a bonehead, a bitwise and on the ord is needed. I'm dealing with either 512MB or 4GB files. When I'm working with 512M, Randal's code flies, but because of the slurp, I think I'll have to go to jmcnamara's when I deal with 4G. Now I'm looking at minutes, rather than hours - thanks!
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.