BugLOG
 
ENTRY FOR 02/07/2007

Converting data types in Perl

I need to take a bunch of hex and parse it into individual fields. I want to use Perl to do it. I need to know what kind of support Perl has for data conversion. After reading this I would say I'm in good shape =)

Perl 5.8 Documentation - Data: Numbers

Pack and unpack are very powerful but also very difficult to grasp.

http://perldoc.perl.org/functions/pack.html
http://perldoc.perl.org/functions/unpack.html

Samples:

#! /usr/bin/perl -w

print "\n\n\n\n";

$bmem = "10101010101010100101001011111011";
$mem = "afdcdfca03782da77355edca";

#print "$mem\n";
#my( $hex ) = unpack( 'H*', $mem );
#print "$hex\n";

print "\n";
$result = bintodec($bmem);
print "$result = bintodec of $bmem";
print "\n\n";
$result = bintohex($bmem);
print "$result = bintohex of $bmem";

# 32 bit word
sub bintodec {
unpack( "N", pack( "B32", substr("0" x 32 . shift, -32) ) );
}

sub bintohex {
unpack( "H8", pack( "B32", substr("0" x 32 . shift, -32) ) );
}

print "\n\n\n\n";

$bin = "1000101";
$result = bintohex($bin);
print "$result = bintohex of $bin \n\n";



return to BugLOG home

return to home page