Bit::Twiddling - Low-level bit-twiddling hacks
Version 0.07 - 2018-08-31
use Bit::Twiddling 'count_set_bits'; my $number = 0b1111_0001; my $set_bits = count_set_bits($number); # 5 printf "There are %d ones in 0b%b\n", $set_bits, $number # There are 5 ones in 0b11110001 use Bit::Twiddling 'nearest_higher_power_of_2'; print nearest_higher_power_of_2( 0); # 1 print nearest_higher_power_of_2(1000); # 1024 print nearest_higher_power_of_2(1024); # 1024
This library is a collection of bit-manipulation functions written in C, all taken from the Bit Twiddling Hacks webpage.
Nothing is exported by default, but the following functions are available for export by name
count_set_bits
nearest_higher_power_of_2
Additionally, you can request the export of all functions by use Bit::Twiddling ':all'.
use Bit::Twiddling ':all'
The functions in this module all expect a single 64-bit integer argument, but will convert string to numeric if needed (and give an Argument "whatevs" isn't numeric in subroutine entry warning). If the argument is undef, it will also be treated as if it were zero and generate a Use of uninitialized value in subroutine entry warning.
Argument "whatevs" isn't numeric in subroutine entry
undef
Use of uninitialized value in subroutine entry
This distribution is designed to work with 64-bit ints and has NOT BEEN TESTED WITH 32-BIT PERLS. I think it should be OK but I know one test in nearest.t will definately fail.
nearest.t
$bits = count_set_bits($number);
count_set_bits will return the count of how many bits are set (1) in the binary representation of $number. $number is assumed to be compatible with C's long int type (probably 64-bits).
$number
long int
$power_of_2 = nearest_higher_power_of_2($number);
nearest_higher_power_of_2 will return the largest power-of-two that is greater-than-or-equal-to $number.
There are two scripts in the examples folder of the dist.
examples
This script contains the original C code that was used with Inline::C to generate the module's XS.
Inline::C
Some benchmarks of this module versus various pure Perl implementations.
Brian Greenfield <briang at cpan dot org>
XXX github
Please use report any bugs you find to GitHub issues.
* Steve Bertrand's Wrapping a C shared library with Perl and XS tutorial
* Bit Twiddling Hacks
* MetaCPAN's online POD renderer
Copyright 2018 Brian Greenfield
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See The "Artistic License"
To install Bit::Twiddling, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Bit::Twiddling
CPAN shell
perl -MCPAN -e shell install Bit::Twiddling
For more information on module installation, please visit the detailed CPAN module installation guide.