in reply to counting set bits in binary file

Besides the performance issue you mentioned, I don't even think that your code works.

You need to fix couple of things:

  1. you need & not |
  2. you need to do an ord()

Test this:

my $c = chr(0xff); my $sum = 0; if ($c) { (ord($c) & 0x01) && ($sum++); (ord($c) & 0x02) && ($sum++); (ord($c) & 0x04) && ($sum++); (ord($c) & 0x08) && ($sum++); (ord($c) & 0x10) && ($sum++); (ord($c) & 0x20) && ($sum++); (ord($c) & 0x40) && ($sum++); (ord($c) & 0x80) && ($sum++); } print $sum;

Your code would look like this (there is no need to count the size of the file, I leave it to you to fix the performance)

use strict; use warnings; open(FIN,"perl.exe") or die "cant open file\n"; my $sum = 0; my $c; while (read(FIN, $c, 1)) { if ($c) { (ord($c) & 0x01) && ($sum++); (ord($c) & 0x02) && ($sum++); (ord($c) & 0x04) && ($sum++); (ord($c) & 0x08) && ($sum++); (ord($c) & 0x10) && ($sum++); (ord($c) & 0x20) && ($sum++); (ord($c) & 0x40) && ($sum++); (ord($c) & 0x80) && ($sum++); } } print "$sum bits are set\n";