in reply to Re: how to pack bits, flags and masks
in thread how to pack bits, flags and masks

thanks, it does seem simpler without 'pack' and I can even count the set bits with a for loop to test each in turn.

I'd been hoping to use this fragment from Programming Perl (ch.29.2.189. unpack):
"The following efficiently counts the number of set bits in a bitstring:
$setbits = unpack "%32b*", $selectmask;

but for me

$value = 5242880; $value = $value | 0x0011; $setbits = unpack "%32b*", $value; printf "$setbits bits are set in %#.8x\n", $value;
gives
25 bits are set in 0x00500011

so my understanding is still inadequate. If you can bear to explain, it would be much appreciated (though I can use the for loop to count bits instead)

thanks

Replies are listed 'Best First'.
Re^3: how to pack bits, flags and masks
by ikegami (Patriarch) on Nov 15, 2004 at 19:51 UTC

    $setbits = unpack "%32b*", $selectmask;
    should be:
    $setbits = unpack "%32b*", $packedmask;
    so:
    $setbits = unpack('%32b*', pack('N', $selectmask));
    does the trick
    print(unpack("%32b*", pack('N', 0x00500011)), $/);  # 4