in reply to Re: 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)
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
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 |