I have an array with some integers, and I would like to convert it to a string in hexadecimal format. This is the code I use, and it works fine. I just wonder if there is a simpler way to do it.
my @arr = get_tw() ; ##array of integer
for(my $i=0;$i<@arr;$i++){
$arr[$i]= sprintf('%02x',$arr[$i]); ##overwrite with the hex value
}
my $string = join('',@arr); ##build a string from a array
using pack/unpack:
my $string = join '', unpack('H*', pack('c*',@arr));
map. This avoids the intermediate array variable, if you don't need it for anything else.
my $string = join '', map { sprintf '%02x', $_ } get_tw();
Full example:
use warnings;
use strict;
sub get_tw { return 8 .. 15 }
my $string = join '', map { sprintf '%02x', $_ } get_tw();
print "$string\n";
Output:
08090a0b0c0d0e0f
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With