in reply to counting set bits in binary file


Here is one way with a more efficient count using the unpack checksum:
#!/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:

#!/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__
But a pure lookup table (as suggested above and previously) would be fastest of all.

--
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

    That doesn't work:

    >perl -le "print(unpack('%32b*', 0x13))" 7

    There are 3 bits set in 0x13, not 7.

    Sorry, my mistake.

    >perl -le "print(unpack('%32b*', chr(0x13)))" 3