nadadogg has asked for the wisdom of the Perl Monks concerning the following question:

I've got a problem with something I'm currently working on. All that I have needed to use perl for up until now was some pretty basic text manipulating. Nothing too fancy, with the help of some of the monks here, I was able to come out of it great, learning a lot. Now, there is a new problem. I've got a file that is pretty much raw binary data, and an old solution with a ksh script under unix that did this:
cc=`hd -bx -s 29 -n 3 <"$filename"|tr -d '[ " " ]'|awk '{print $2}'`
In some parts, there is an offset as well, which I understand how to work with. The problem I'm hitting is that I do not know how to emulate this in perl. The HD command on our old Unix machine was set like this:
hd-- display files in a hexadecimal format hd [ -format (bx is binary)] [ -s(offset)] [-n (count)] [filename] tr - translate characters the -d Deletes all input characters in the input string.
I found this module that had something similar to what I'm trying to do, but I don't understand how to use it. Any help is much appreciated. How do I convert between decimal and binary?

Replies are listed 'Best First'.
Re: Picking certain values to convert from binary to decimal
by Zaxo (Archbishop) on Jan 03, 2004 at 19:53 UTC

    If I understand correctly, you want to extract the three bytes starting at offset 29. You can get those with substr and then unpack them. Since your file is binary, let's read the first 32 bytes only, by setting $/ to a reference to 32.

    my @chars; { local $/ = \32; open my $fh, '<', $name or die $!; binmode $fh; local $_ = <$fh>; @chars = unpack 'CCC', substr $_, 29, 3; close $fh or die $!; } print "@chars", $/; # quoted only to put space between values
    The conversion is done by unpack, according to the template given in its first argument. "Decimal" really has little to do with it. The decimal string is produced by the stringification of a numeric value.

    After Compline,
    Zaxo

      This output values similar to what I used before, and even though I found an alternate way of doing it(using some proprietary work stuff), your stuff helped me understand how to use it. Thanks a bunch.