[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: OT: Some advice on perl: read byte to hex string



On Wed, Sep 20, 2006 at 01:29:44PM +0700, Welly Hartanto wrote:
> #Loop through the whole data
> for ($i=0; $i < (length($gotit)); $i++) {
>     my $c = substr($gotit, $i, 1);
>     $c1 = $c & 0xF0;                          #get the high nibble
>     $c1 = $c1 >> 4;                           #
>     $c1 = $c1 & 0x0F;                         #
>     $str1 = hex($c1);                         #convert to hex

Well, no.  This converts *from* hex:

$ perl -e 'print hex(12), "\n"'
18

>     $c2 = $c & 0x0F;                          #get the low nibble
>     $str2 = hec($c2);                         #convert to hex
>     print $str1 . $str2;                      #display the string
> }

Anyhow, though, is there a reason for doing this the hard way instead of:

#Loop through the whole data
for ($i=0; $i < (length($gotit)); $i++) {
  my $c = substr($gotit, $i, 1);
  print sprintf "%0.2x", ord($c);
}

or, in a slightly more perlish idiom:

my @data = split //, $gotit;
foreach my $c (@data) {
  print sprintf "%0.2x", ord($c);
}

or, even a little perlier:

my @data = unpack("c*", $gotit);
foreach my $c (@data) {
  print sprintf "%0.2x", $c;
  # Note that ord() isn't needed this time because unpack already converted
  # from characters to ASCII values
}

-- 
The freedoms that we enjoy presently are the most important victories of the
White Hats over the past several millennia, and it is vitally important that
we don't give them up now, only because we are frightened.
  - Eolake Stobblehouse (http://stobblehouse.com/text/battle.html)



Reply to: