dwhite20899 has asked for the wisdom of the Perl Monks concerning the following question:
It works, but it's slow.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";'
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!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: counting set bits in binary file
by jmcnamara (Monsignor) on Jul 16, 2005 at 02:29 UTC | |
by ikegami (Patriarch) on Jul 16, 2005 at 03:35 UTC | |
|
Re: counting set bits in binary file
by hv (Prior) on Jul 16, 2005 at 01:42 UTC | |
|
Re: counting set bits in binary file
by merlyn (Sage) on Jul 16, 2005 at 04:25 UTC | |
by snowhare (Friar) on Jul 18, 2005 at 00:41 UTC | |
|
Re: counting set bits in binary file
by pg (Canon) on Jul 16, 2005 at 02:48 UTC | |
|
Re: counting set bits in binary file
by blazar (Canon) on Jul 18, 2005 at 08:57 UTC |