#!perl use warnings; use strict; # the following subroutines couns the number of bits in an 8-bit integer sub sadd8_a { # my first solution -- without looking closely to your code my($x) = @_; my $n = 0; for (my $k = 1; $k < 0x100; $k <<= 1) { 0 != ($x & $k) and $n++; } $n; } sub sadd8_b { # one of your solutions, modified a bit my ( $iDays ) = @_; my $iRes = 0; for ( 1, 2, 4, 8, 16, 32, 64, 128 ){ if ( $iDays & $_ ){ $iRes++; } } return $iRes; } sub sadd8_c { my($x) = @_; $x = ($x & 0b01010101) + ($x >> 1 & 0b01010101); $x = ($x & 0b00110011) + ($x >> 2 & 0b00110011); ($x & 0b00001111) + ($x >> 4); } # let's print an example for my $n (0 .. 31) { print sadd8_a($n), " "; } print "\n"; # test for my $n (0 .. 255) { my $a = sadd8_a($n); my $b = sadd8_b($n); my $c = sadd8_c($n); $a == $b && $b == $c or die "wrong results: $n $a $b $c"; } __END__