Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

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

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


in reply to Re^2: 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)

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; }

C:/Strawberry/perl/bin\perl.exe -w d:/tmp/pm/hex_groups.pl 0 => 0 00 000 0000 2 => 2 02 002 0002 20 => 1 4 14 014 0014 200 => c 8 c8 0c8 00c8 2000 => 7 d 0 07 d0 7d0 07d0 20000 => 4 e 2 0 4e 20 004 e20 4e20 200000 => 3 0 d 4 0 03 0d 40 030 d40 0003 0d40 2000000 => 1 e 8 4 8 0 1e 84 80 1e8 480 001e 8480 20000000 => 1 3 1 2 d 0 0 01 31 2d 00 001 312 d00 0131 2d00 200000000 => b e b c 2 0 0 0b eb c2 00 00b ebc 200 0beb c200 2000000000 => 7 7 3 5 9 4 0 0 77 35 94 00 077 359 400 7735 9400 20000000000 => 4 a 8 1 7 c 8 0 0 04 a8 17 c8 00 4a8 17c 800 0004 a817 c800 Compilation finished at Mon Aug 30 16:28:18

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-25 21:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found