in reply to Split any number into string of 8-bit hex values (=1 byte)

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11136191 use warnings; for my $n (0, 2, 20, 200, 2000, 20000, 200000) { my @bytes = reverse sprintf('%016X', $n) =~ s/^(?:00)*\B//r =~ /../g +; print "$n => @bytes\n"; }

Outputs:

0 => 00 2 => 02 20 => 14 200 => C8 2000 => D0 07 20000 => 20 4E 200000 => 40 0D 03

Replies are listed 'Best First'.
Re^2: Split any number into string of 8-bit hex values (=1 byte)
by Marshall (Canon) on Aug 30, 2021 at 10:56 UTC
    Your regex code is impressive to say the least!
    It replicates my output verbatim.

    But this fuzzy requirement about the number of bytes to be output seems odd to me.
    I updated my post with what I hope is a clear question to the OP.

    I guess we shall see what, if anything develops from that.

      I do have another regex ready in case the OP wants answers that are ONLY 1, 2, 4, or 8 bytes long.

      We'll just have to wait...

        Yes please :-) If I'd convert anything from a quad and then remove unnecessary leading zeros so that I'd end up with 1, 2, 4 or 8 bytes I'm thinking that this should work. What does the regex look like?
Re^2: Split any number into string of 8-bit hex values (=1 byte)
by Bod (Parson) on Aug 30, 2021 at 17:57 UTC

    Whenever I begin to think that I am getting anywhere in Perl, I look at one of your elegant regexps and realise just how far I still have to go!