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