Tuesday, May 5, 2009

Perl: Convert HEX string into character string

Share at Facebook

At my last post http://icfun.blogspot.com/2009/05/perl-convert-character-string-into-hex.html I've mentioned about character string conversion into HEX string.

Now, its time to do the reverse task. You'll be given a Hex string, and you'll need to convert it into character string. The idea will be similar as last one. Just need to pick-up two hex digit 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 digit 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 I have converted the hex code into integer number, and then using chr() function, I have converted the ascii number into it's character code.


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...

Work like a charm