fork download
  1. #!/usr/bin/perl
  2. # Idiom #84 Count bits set in integer binary representation
  3. # https://p...content-available-to-author-only...s.org/idiom/84/count-bits-set-in-integer-binary-representation
  4.  
  5. @values = (
  6. 19,
  7. 2**31 - 1,
  8. 0b0111101000110001,
  9. 0xA1,
  10. 0xA3,
  11. );
  12.  
  13. foreach my $i ( @values ) {
  14. $b = pack 'i', $i;
  15. $c = unpack '%b*', $b;
  16. printf "hex %X dec %d bin %b has %d bits\n", $i, $i, $i, $c;
  17. }
  18.  
Success #stdin #stdout 0.01s 5396KB
stdin
Standard input is empty
stdout
hex 13 dec 19 bin 10011 has 3 bits
hex 7FFFFFFF dec 2147483647 bin 1111111111111111111111111111111 has 31 bits
hex 7A31 dec 31281 bin 111101000110001 has 8 bits
hex A1 dec 161 bin 10100001 has 3 bits
hex A3 dec 163 bin 10100011 has 4 bits