ItsJustMe
ItsJustMe

Reputation: 137

Perl hex string to binary string

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?

Upvotes: 7

Views: 10603

Answers (3)

Qtax
Qtax

Reputation: 33908

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

print pack 'H*', '41424344';

Output:

ABCD

Upvotes: 16

Liudvikas Bukys
Liudvikas Bukys

Reputation: 5870

s/([a-f0-9][a-f0-9])/chr(hex($1))/egi;

Upvotes: 1

mob
mob

Reputation: 118605

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.

Upvotes: 1

Related Questions