perlpackcrc16uint16

Wrong access to struct elements in Perl


I am writing a Perl script capable of loading a binary RAW file (.bin file extension), calculate the CRC-16 (unsigned short, 16bits ~ 2 bytes), and store this CRC in a file trailer, using the following commands:

my $ctx = Digest::CRC->new( type => 'crc16' );  #OK :)
open my $FH, '<:raw', $inFile or die $!;        #OK :)
$ctx->addfile(*$FH);                            #OK :)
print ("$inFile CRC16 value = 0x");             #OK :)
my $digest = $ctx->hexdigest;                   #OK :)
print $digest, "\n";                            #OK :)
print WRITEHANDLE pack("n*", $digest);          #NOT OK :(

Last command raises a warning, and more the CRC is not stored in the correct way

enter image description here

and in the binary output last 2 bytes are not once calculated/expected

enter image description here

It is clear that I am not using properly the pack method for storing the value, but from the pack() MAN

enter image description here

What is the correct Template for pack() in this case?


Solution

  • As per the warning, you have the string 6c5b, but pack 'n' expects a number. $ctx->digest produces that number.

    print WRITEHANDLE pack 'n', $ctx->digest;
    

    That said, with the hex representation of the digest, you can use pack 'H*' (as long as it's left-padded with zeroes).

    print WRITEHANDLE pack 'H*', $ctx->hexdigest;