I wasn't going to follow up but decided to do so since there is a small but
subtle bug in my original post.
I wouldn't want to mislead you Todd.

The \d has been changed to [0..9] as the expected input would only ever be
in that range.  (\d includes Unicode Characters)
I've also included an alignment parameter (shadow'ing the sub written by
you Todd).

sub sbprint( Int $n, Int :$alignment = 8) {
        my Int $padding = $alignment + $n.msb - ( $n.msb +& ( $alignment  -
1 ) );
        '0b' ~ "\%0{$padding}b".sprintf($n).comb(/<[0..9]> ** { $alignment
}/).join('_')
}

say sbprint 0x04F842;
say sbprint 0x04F842, :alignment(4);

# ./test.pl6
0b00000100_11111000_01000010
0b0100_1111_1000_0100_0010



I'm not suggesting you use my routine as I have no idea about what you're
requirements are but wanted to be sure my contribution to your problem was
sound.

Take Care.

On Wed, Feb 5, 2020 at 10:29 PM ToddAndMargo via perl6-users <
perl6-us...@perl.org> wrote:

> On 2020-02-03 13:51, ToddAndMargo via perl6-users wrote:
> > Hi All,
> >
> > Is ther a way to get
> >
> > $ p6 'my uint8 $u = 84; printf "\$u = <%08s>\n", $u;'
> > $u = <00000084>
> >
> > to print
> >
> > $u = <0000_0084>
> >
> > ?
> >
> >
> > Many thanks,
> > -T
>
> Hi All,
>
> Just to torment myself, I wrote a sub to do this:
>
> .......................................
> sub sbprint( UInt $b )  {
>     my $bits  = $b.UInt.msb + 1;
>     my $bytes = $bits div 8;
>     if ($bits % 8 ) > 0  { $bytes += 1 };
>     # say "bits = $bits   bytes = $bytes";
>     my Str $bitstr = "";
>
>     loop ( my $i = 0; $i < $bytes; $i += 1 )  {
>        my $j = ( $b +> ( $i * 8 ) ) +& 0xFF;
>        my $k = sprintf "_%08s", $j.base(2);
>        # say "b = $b.base(2)   i = $i   j = $j.base(2)   k = $k";
>        $bitstr = $k ~ $bitstr;
>        # say $bitstr;
>     }
>     $bitstr = "0b" ~ $bitstr;
>     $bitstr ~~ s/ 0b_ /0b/;
>     return $bitstr;
> }
>
> say sbprint 0x04F842;
> say 0x04F842.base(2);
> .......................................
>
> $ intTest.pl6
> 0b00000100_11111000_01000010
>         100 11111000 01000010    # spaces added by me
>


-- 
__________________

:(){ :|:& };:

Reply via email to