Convert character string into HEX string in Perl

Let's learn about converting a character string into a HEX string. For example you have a string "abcd", it will convert it into HEX string as "61626364". Means just take each character from the string, and get its ascii code, and convert it into HEX.

I'm using regular expression (REGEX) to do this conversion. Below is the code.




## Initial string
$string = "abcdefjhijklmnopqrstuvwx";

## convert each characters from the string into HEX code
$string =~ s/(.)/sprintf("%x",ord($1))/eg;

print "$string\n";

The above code will convert the provided string string into its corresponding hexadecimal code. Using regex we are picking up each characters from the string, and then obtaining the ascii code using ord() function. Then using sprintf() we are printing as HEX code.

If you want the output in UPPERCASE you'd just need to make %x into %X inside your sprintf() function.

$string =~ s/(.)/sprintf("%X",ord($1))/eg;


The output will be as below for Lowercase, and Upper case:

6162636465666a68696a6b6c6d6e6f707172737475767778
6162636465666A68696A6B6C6D6E6F707172737475767778


The reverse one is at convert hex string into character.

Comments

Anonymous said…
Many thanks, this saved me a lot of time.

But I think you need to use %02x rather than just %x, otherwise control chars below 0x10 will only show as one digit, which gets very confusing!
Anonymous said…
Even easier:

Convert to hex with
$hstring = unpack ("H*",$pstring);

Get it back with
$pstring = pack (qq{H*},qq{$hstring});
kannibal615 said…
Thank your very much friend

realy is a good post

thanks a lot

Kannibal615
Anonymous said…
Thanks for this.

A word of warning: you should use the '/seg' modifiers, not just '/eg', if the string contains new line characters.
Keith said…
sub DumpString {
my $s = shift || "";
my @a = unpack('C*',$s);
my $o = 0;
my $i = 0;
print "\tb0 b1 b2 b3 b4 b5 b6 b7\n";
print "\t-- -- -- -- -- -- -- --\n";
while (@a) {
my @b = splice @a,0,8;
my @x = map sprintf("%02x",$_), @b;
my $c = substr($s,$o,8);
$c =~ s/[[:^print:]]/ /g;
printf "w%02d",$i;
print " "x5,join(' ',@x),"\n";
$o += 8;
$i++;
}
}
Keith said…
I didn't write this function; don't remember who did... works great and the formatting makes the text very easy to read.

sub DumpString {
my $s = shift || "";
my @a = unpack('C*',$s);
my $o = 0;
my $i = 0;
print "\tb0 b1 b2 b3 b4 b5 b6 b7\n";
print "\t-- -- -- -- -- -- -- --\n";
while (@a) {
my @b = splice @a,0,8;
my @x = map sprintf("%02x",$_), @b;
my $c = substr($s,$o,8);
$c =~ s/[[:^print:]]/ /g;
printf "w%02d",$i;
print " "x5,join(' ',@x),"\n";
$o += 8;
$i++;
}
}