http://www.perlmonks.org?node_id=11136258


in reply to Re^6: Split any number into string of 8-bit hex values (=1 byte)
in thread Split any number into string of 8-bit hex values (=1 byte)

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.

Replies are listed 'Best First'.
Re^8: Split any number into string of 8-bit hex values (=1 byte)
by soonix (Canon) on Aug 31, 2021 at 07:04 UTC
    Note that for 200, C8 is a negative number, so the 00 is required to make it so that C8 00 is positive.
    Ah, that might be the reason for that odd trailing '00' in the OP

      How does an 8-bit register in an I2C device "know" that an 0xc8 byte started out as 20010 or as -5610? One can make similar arguments about 16- and 32-bit registers.

      I share the misgivings expressed by LanX here.


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