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

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



On Tuesday 19 September 2006 23:29, Welly Hartanto wrote:

> 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;                         #

$c is not a byte; it is a variable that contains a 1-byte string. So doing 
bitwise operations like & on it won't do what you expect. What it will do is 
convert $c to a numeric value (if possible) and then perform the &. For most 
of the data you are probably reading, it's converting it to 0 because it's 
not numeric to begin with. The rest of the time, it would convert it to some 
number between 1 and 9.

Presumably, what you want is the value of the byte from 0 to 255. So, you 
first need to convert $c to that value using the ord function.

$c1 = ((ord($c) & 0xf0) >> 4) & 0x0f;

>     $str1 = hex($c1);                         #convert to hex

I don't know what this hex function is supposed to do. Most likely, you want

$str1 = sprintf("%02x", $c1);

>     $c2 = $c & 0x0F;                          #get the low nibble
>     $str2 = hec($c2);                         #convert to hex

$str2 = sprintf("%02x", ord($c) & 0x0f);

-- 
Dave Carrigan
Seattle, WA, USA
dave@rudedog.org | http://www.rudedog.org/
UNIX-Apache-Perl-Linux-Firewalls-LDAP-C-C++-DNS-PalmOS-PostgreSQL-MySQL-Postfix

Dave is currently listening to John Doe - She's Not (Forever Hasn't Happened 
Yet)

Attachment: pgpL7H4O_uhvd.pgp
Description: PGP signature


Reply to: