Another approach:

Win8 Strawberry 5.8.9.5 (32) Sun 08/29/2021 18:20:29 C:\@Work\Perl\monks >perl -Mstrict -Mwarnings for my $n (qw(2 20 200 2000 20000 200000 2000000)) { print "$n -> "; print join ' ', unpack '(H2)*', pack 'V', $n; print "\n"; } ^Z 2 -> 02 00 00 00 20 -> 14 00 00 00 200 -> c8 00 00 00 2000 -> d0 07 00 00 20000 -> 20 4e 00 00 200000 -> 40 0d 03 00 2000000 -> 80 84 1e 00
As with LanX's solution, leading | trailing zeros are present, but they are present in some of the OPed examples as well and I can't figure out when you do and don't want them.

Update: If you're using a 64-bit Perl, you have the 'Q' pack template specifier (update: which uses native endianity by default; see below), so:

Win8 Strawberry 5.30.3.1 (64) Sun 08/29/2021 20:05:59 C:\@Work\Perl\monks >perl -Mstrict -Mwarnings for my $n (qw(2 20 200 2000 20000 200000 2000000)) { print "$n -> "; # print join ' ', unpack '(H2)*', pack 'Q', $n; # original print join ' ', unpack '(H2)*', pack 'Q<', $n; print "\n"; } ^Z 2 -> 02 00 00 00 00 00 00 00 20 -> 14 00 00 00 00 00 00 00 200 -> c8 00 00 00 00 00 00 00 2000 -> d0 07 00 00 00 00 00 00 20000 -> 20 4e 00 00 00 00 00 00 200000 -> 40 0d 03 00 00 00 00 00 2000000 -> 80 84 1e 00 00 00 00 00
(but you get a lot more trailing zeroes :). (Update: The 'Q' specifier should be used with a '<' little-endian specifier to force the desired byte ordering. 'Q' alone - as used in my originally posted code - uses native byte ordering, whatever that may be.)


Give a man a fish:  <%-{-{-{-<


In reply to Re: Split any number into string of 8-bit hex values (=1 byte) (updated) by AnomalousMonk
in thread Split any number into string of 8-bit hex values (=1 byte) by drsweety

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.