Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Split any number into string of 8-bit hex values (=1 byte)

by LanX (Saint)
on Aug 29, 2021 at 21:38 UTC ( [id://11136192]=note: print w/replies, xml ) Need Help??


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

maybe
DB<20> print join " ", reverse split /(..)/ , sprintf "%06x\n", 2*10* +*$_ for 0..5 02 00 00 14 00 00 c8 00 00 d0 07 00 20 4e 00 40 0d 03 DB<21>

I'm not sure why you want low bytes first, but please note you had trailing 00s in your example too.

update

this will give you the number of necessary bytes

DB<29> say 1+int (log (2*10**$_)/log 256) for 0..5 1 1 1 2 2 3

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re^2: Split any number into string of 8-bit hex values (=1 byte)
by LanX (Saint) on Aug 30, 2021 at 14:00 UTC
    log(0) is undefined, so I designed a custom function hexbytes which returns a list of 0 padded bytes and special casing '00'.

    Please note how I kept the reverse and join outside for generic flexibility of use.

    NB: you must still take care of negative $n!

    use strict; use warnings; use feature "say"; sub hexbytes { my ($n)=@_; my $nibbles = $n ? int( log($n)/log 256 )+1 : 1 ; # 00 has no log $nibbles *= 2; # 2 nibbles = 1 byte return sprintf( '%0*x', $nibbles, $n ) =~ /(..)/g; } say "$_ => ", join " ", reverse hexbytes($_) for 0,2,20,200,2000,20000 +,200000;

    C:/Strawberry/perl/bin\perl.exe -w d:/tmp/pm/hex_reverse.pl 0 => 00 2 => 02 20 => 14 200 => c8 2000 => d0 07 20000 => 20 4e 200000 => 40 0d 03 Compilation finished at Mon Aug 30 15:57:08

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

      Here a more generic solution, the grouping is free now

      (left the reverse out for better testing)

      use strict; use warnings; use feature "say"; sub hexgroups { my ( $n, $group ) = @_; die "Can't handle negative $n" if $n <0; $group //= 2; # default 1 byte = 2 nibbles my $nibbles = $n ? int( log($n)/log 16**$group ) +1 : 1 ; # 00 has no log $nibbles *= $group; # zero padding my @list = sprintf( '%0*x', $nibbles, $n ) =~ /(.{$group})/g; return @list; } for my $n (0, map { 2*"1e$_"} 0..10) { say "$n => "; say "\t"x2, join " ", hexgroups($n, $_) for 1,2,3,4; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11136192]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (6)
As of 2024-03-28 15:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found