in reply to counting set bits in binary file
#!/usr/bin/perl -wl use strict; my $count = 0; my $long; open FILE, "file.txt" or die "Couldn't open file: $!\n"; binmode FILE; while (read FILE, $long, 4) { $count += unpack'%32b*', $long; } print $count; __END__
Or make it more efficient by memoising the calculated values:
But a pure lookup table (as suggested above and previously) would be fastest of all.#!/usr/bin/perl -wl use strict; my $count = 0; my %lookup; my $byte; open FILE, "file.txt" or die "Couldn't open file: $!\n"; binmode FILE; while (read FILE, $byte, 1) { next unless ord $byte; if ($lookup{$byte}) { $count += $lookup{$byte}; } else { $count += $lookup{$byte} = unpack'%8b*', $byte; } } print $count; __END__
--
John.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: counting set bits in binary file
by ikegami (Patriarch) on Jul 16, 2005 at 03:35 UTC |