7

I'm trying to convert a string of hex digits to a binary string. If my input string is 41424344, then I would want the string to store "ABCD". How can this be done?

3 Answers 3

16

You can do it without using regex with help of pack:

print pack 'H*', '41424344';

Output:

ABCD
1

The canonical method is

$input_string =~ s/(..)/chr(hex($1))/ge;

This reads two characters at a time from the input, calling hex (converting a hexidecimal number to a decimal number) and then chr (converting a decimal number to a character) on each input.

2
  • @daxim - Citing anything as canon in Perl risks starting a holy war and I respect your difference of opinion. The CGI module currently uses the .../chr hex $1/ge idiom, but upon further research I find that its technique to unescape HTML has gone through many other incarnations.
    – mob
    Commented Mar 26, 2012 at 17:37
  • 2
    Lincoln Stein, the creator of CGI.pm, was anything but canonical. He invented ways of doing things that nobody else would use. :) Commented Mar 26, 2012 at 18:09
1
s/([a-f0-9][a-f0-9])/chr(hex($1))/egi;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.