G'day gblack,
Welcome to the Monastery.
Here's one way to do this using Math::BigInt::GMP.
#!/usr/bin/env perl use 5.010; use strict; use warnings; use Math::BigInt lib => 'GMP'; for my $number (57, '886545601050728061451195', '0x' . 'b' x 20) { say "Number: $number"; say "Array: @{get_array($number)}"; say 'Bits: ', scalar @{get_array($number)}; for (0 .. 5) { say "Bit $_: ", is_bit_set($number, $_); } } { my %cache; sub get_array { $cache{$_[0]} // gen_array($_[0]) } sub is_bit_set { ($cache{$_[0]} // gen_array($_[0]))->[$_[1]] } sub gen_array { $cache{$_[0]} = [ reverse split //, substr Math::BigInt::->new($_[0])->as_bi +n(), 2 ] } }
I tested with your example number (57) and an 80-bit number in stringified, decimal (886545601050728061451195) and hexidecimal (0xbbbbbbbbbbbbbbbbbbbb) representations:
Number: 57 Array: 1 0 0 1 1 1 Bits: 6 Bit 0: 1 Bit 1: 0 Bit 2: 0 Bit 3: 1 Bit 4: 1 Bit 5: 1 Number: 886545601050728061451195 Array: 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 +1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 + 0 1 1 1 0 1 1 1 0 1 1 1 0 1 Bits: 80 Bit 0: 1 Bit 1: 1 Bit 2: 0 Bit 3: 1 Bit 4: 1 Bit 5: 1 Number: 0xbbbbbbbbbbbbbbbbbbbb Array: 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 +1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 + 0 1 1 1 0 1 1 1 0 1 1 1 0 1 Bits: 80 Bit 0: 1 Bit 1: 1 Bit 2: 0 Bit 3: 1 Bit 4: 1 Bit 5: 1
If you're not going to be doing multiple operations on the same number, you might be better off without the cache.
I see others have suggested solutions. I'd tailor these to your specific requirements and then Benchmark.
— Ken
In reply to Re: Turning very larger numbers into an array of bits
by kcott
in thread Turning very larger numbers into an array of bits
by gblack
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |