Convert-Binary-C

 view release on metacpan or  search on metacpan

bin/convert.PL  view on Meta::CPAN

#-------------------------------------------------
# Pack a Perl data structure into a binary string.
# Note that not all members need to be specified.
#-------------------------------------------------

my $binary = $c->pack( 'convert', {
  word => [-30000, 4711],
  c32  => { dword => 0x01020304 }
} );

#-------------------------------------------------------
# Just a demonstration that pack does the right thing...
#-------------------------------------------------------

if( $c->sizeof( 'convert' ) == length $binary ) {
  print "\nYup, the size matches!\n";
}

#-------------------------------------------------------
# Hexdump the binary string.
# Note that all padding regions are initialized to zero.
#-------------------------------------------------------

print "\nBinary: ", hexdump( $binary ), "\n\n";

#---------------------------------------------------------------
# Unpack the binary string and dump the returned data structure.
#---------------------------------------------------------------

my $data = $c->unpack( 'convert', $binary );
print Data::Dumper->Dump( [$data], ['data'] );

#------------------------------------------------------
# You can modify selected elements in the binary string
# using the 3-argument version of 'pack'.
#------------------------------------------------------

# only 'dword' will be modified
$c->pack( 'convert', { dword => -559038737 }, $binary );
print "\nBinary: ", hexdump( $binary ), "\n\n";
print Dumper( $c->unpack( 'convert', $binary ) );

#--------------------------------------------------
# You can also use pack/unpack on compound members.
#--------------------------------------------------

my $array = $c->unpack( 'convert.c32.bytes', 'ABCD' );
print "\n\$array = [ @$array ]\n";

#==========================================================
#                     SUBROUTINES
#==========================================================

sub hexdump
{
  join ' ', map { sprintf "%02X", $_ } unpack "C*", $_[0];
}
!NO!SUBS!

close OUT or die "Can't close $file: $!";
chmod 0755, $file or die "Can't reset permissions for $file: $!\n";



( run in 0.442 second using v1.01-cache-2.11-cpan-cdf2f3d4e48 )