Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl hex string to binary string

Tags:

perl

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?

like image 440
ItsJustMe Avatar asked Mar 26 '12 16:03

ItsJustMe


3 Answers

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

print pack 'H*', '41424344';

Output:

ABCD
like image 200
Qtax Avatar answered Dec 04 '22 15:12

Qtax


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.

like image 40
mob Avatar answered Dec 04 '22 16:12

mob


s/([a-f0-9][a-f0-9])/chr(hex($1))/egi;
like image 20
Liudvikas Bukys Avatar answered Dec 04 '22 16:12

Liudvikas Bukys