Tuesday, May 5, 2009

Perl: Convert character string into HEX string


Share at Facebook

Lets 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 character 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 it's corresponding HEX code. Using regex i'm picking up the each character from the string, and get the ascii code using ord() function. Then using sprintf() I've just printed as HEX code.

If you want the output as UPPERCASE, you'll 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 http://icfun.blogspot.com/2009/05/perl-convert-hex-string-into-character.html




6 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++;
}
}