Convert hexadecimal string into character string in Perl

In my last post character string into hex I mentioned about character string conversion into HEX string.

Now, it's time to do the reverse task. We have a hex string and we need to convert it into character string. The idea is similar as last one. Just need to pick-up two hex digits each time, and convert them into character code. Below is the code.


## Initial hex
$string = "6162636465666a68696a6b6c6d6e6f707172737475767778";

## upper/lower case won't be a problem
# $string = "6162636465666A68696A6B6C6D6E6F707172737475767778";

## convert each two digits into char code
$string =~ s/([a-fA-F0-9][a-fA-F0-9])/chr(hex($1))/eg;

print "$string\n";


This time using hex() function we converted the hex code into integer number, and then using chr() function, we converted the ascii number into its character code.

Comments

chorny said…
You can use pack/unpack for this kind of conversions
Chap said…
But how???
Simon said…
perl -le 'print pack("H*","6162636465666a68696a6b6c6d6e6f707172737475767778")'
Anonymous said…
Thanks,
Work like a charm