Converting a string into hex chars?

E

Eric

Hi,

I need to convert a string into a HTML encoded hex equivalent. I'm trying
things along the lines of:
________________________________________________
my $message = 'This is a message with various characters in it.';

my $encmsg = '';
for (my $i=0; $i<length($message); $i++)
{
$encmsg .= "%" . ord(substr($message, $i, 1));
}

print $encmsg;
________________________________________________

But this is producing decimal codes instead of hex ones.

Is there a better way to do this, that works?

Thanks,

Eric
 
H

hubert depesz lubaczewski

Eric wyrze¼bi³(a):
I need to convert a string into a HTML encoded hex equivalent. I'm trying
things along the lines of:
________________________________________________
my $message = 'This is a message with various characters in it.';

perl -le '
$message="This is a message with various characters in it.";
$message =~ s/./sprintf("%%%02x", ord($&))/ges;
print $message'

depesz
 
G

Gunnar Hjalmarsson

Eric said:
I need to convert a string into a HTML encoded hex equivalent. I'm
trying things along the lines of:
________________________________________________
my $message = 'This is a message with various characters in it.';

my $encmsg = '';
for (my $i=0; $i<length($message); $i++)
{
$encmsg .= "%" . ord(substr($message, $i, 1));
}

print $encmsg;
________________________________________________

But this is producing decimal codes instead of hex ones.

Is there a better way to do this, that works?

That works? I can't see that you even tried to convert to hexadecimal
numbers. See the sprintf() function.

$encmsg .= sprintf '%%%02X', ord $_ for split //, $message;

Or check out the URI::Escape module.
 
J

Jay Tilton

: Eric wrote:
: > I need to convert a string into a HTML encoded hex equivalent.

: See the sprintf() function.
:
: $encmsg .= sprintf '%%%02X', ord $_ for split //, $message;

Or even let sprintf() do every bit of the work.

my $encmsg = sprintf "%%%*v02X", '%', $message;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top