>On Fri, 23 Feb 1996, Paul Duda wrote: > >> PowerMac 7100/66 System 7.5.1 >> Macperl v5.0.6r1m >> >> Why does the following script only produce the expected results the first >>time >> the script is run? >> >> for ($i = 0;$i < 5;$i++) { >> vec($vector, $i, 1) = 1; >> print $i, '. Setbits are: ', unpack("%32b*", $vector), "\n"; >> } >> print '$vector is: "', $vector, '" or ', unpack("b*", $vector), "\n"; :::::::::::::::::::::::::::::::: John Peterson's reply on the 24th Feb included the following suggestion:- >One relatively easy way to fix this would be to declare bitcount as a static >array with the values already defined, like this: > >static char bitcount[256] = > { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, > 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, > 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, > 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, > 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, > 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, > 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, > 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, > 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, > 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, > 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, > 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, > 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, > 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, > 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, > 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 } > >...which I just created with the following PERL script (look familiar?): > >for $i (0..255) { > $bitcount = 0; > if ($i & 1) { $bitcount++ } > if ($i & 2) { $bitcount++ } > if ($i & 4) { $bitcount++ } > if ($i & 8) { $bitcount++ } > if ($i & 16) { $bitcount++ } > if ($i & 32) { $bitcount++ } > if ($i & 64) { $bitcount++ } > if ($i & 128) { $bitcount++ } > > unless ($i % 16) { print "\n " } > print "$bitcount, "; >} > >Of course, Matthias would have to incorporate this (or a different fix) into >his code for you. :::::::::::::::::::::::::::::::::::::: In the meantime, using essentially the same algorithm, the following sub routine could be used perhaps: sub bit_count { $bitcount = 0; for ($i = 1; $i <=128; $i = $i*2) { if ($i & @_[0]) { $bitcount++ } } return $bitcount; } For Paul Duda's original example <&bit_count(ord($vector))> always returns 5 as it should. Alan ajf@afco.demon.co.uk