Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an array of integers into a string of HEX

Tags:

perl

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
like image 357
Nik Henri Avatar asked Oct 22 '25 05:10

Nik Henri


2 Answers

using pack/unpack:

my $string = join '', unpack('H*', pack('c*',@arr)); 
like image 134
Pierre Avatar answered Oct 24 '25 03:10

Pierre


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
like image 32
toolic Avatar answered Oct 24 '25 03:10

toolic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!