Assuming you meant "signed" for the second case, here's revised code with extended test cases.

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11136191 use warnings; my @test = map 2 * 10 ** $_, 0 .. 16; for my $n ( 0, @test, map -$_, @test ) { my @bytes = reverse sprintf('%016X', $n) =~ s/^0{8}(0{4}(00)?)?(?=[0-7])//r =~ s/^F{8}(F{4}(FF)?)?(?=[89A-F])//r =~ /../g; print "$n => @bytes\n"; }

Outputs:

0 => 00 2 => 02 20 => 14 200 => C8 00 2000 => D0 07 20000 => 20 4E 200000 => 40 0D 03 00 2000000 => 80 84 1E 00 20000000 => 00 2D 31 01 200000000 => 00 C2 EB 0B 2000000000 => 00 94 35 77 20000000000 => 00 C8 17 A8 04 00 00 00 200000000000 => 00 D0 ED 90 2E 00 00 00 2000000000000 => 00 20 4A A9 D1 01 00 00 20000000000000 => 00 40 E5 9C 30 12 00 00 200000000000000 => 00 80 F4 20 E6 B5 00 00 2000000000000000 => 00 00 8D 49 FD 1A 07 00 20000000000000000 => 00 00 82 DF E4 0D 47 00 -2 => FE -20 => EC -200 => 38 FF -2000 => 30 F8 -20000 => E0 B1 -200000 => C0 F2 FC FF -2000000 => 80 7B E1 FF -20000000 => 00 D3 CE FE -200000000 => 00 3E 14 F4 -2000000000 => 00 6C CA 88 -20000000000 => 00 38 E8 57 FB FF FF FF -200000000000 => 00 30 12 6F D1 FF FF FF -2000000000000 => 00 E0 B5 56 2E FE FF FF -20000000000000 => 00 C0 1A 63 CF ED FF FF -200000000000000 => 00 80 0B DF 19 4A FF FF -2000000000000000 => 00 00 73 B6 02 E5 F8 FF -20000000000000000 => 00 00 7E 20 1B F2 B8 FF

Note that for 200, C8 is a negative number, so the 00 is required to make it so that C8 00 is positive.


In reply to Re^7: Split any number into string of 8-bit hex values (=1 byte) by tybalt89
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.