How can I read unsigned int from binary in Perl?

Say I have a binary that is formatted as

    [unsigned int(length of text)][text][unsigned int(length of text)][text][unsigned int(length of text)][text]

And this template for the file simply repeats. How did I read an unsigned int and print it and then a text block in Perl?

Again, this is a binary file, not a plain text file.

+3
source share
4 answers

Here is a small working example.

#!/usr/bin/perl

use strict;
use warnings;

my $INT_SIZE = 2;
my $filename = 'somefile.bin';

open my $fh, '<', $filename or die "Couldn't open file $filename: $!\n";

binmode $fh;

while ( read $fh, my $packed_length, $INT_SIZE ) {

    my $text = '';
    my $length = unpack 'v', $packed_length;

    read $fh, $text, $length;

    print $length, "\t", $text, "\n";
}

Change INT_SIZE, as well as the size and essence of the decompression pattern (either "v", or "n" or "V" or "N"). See the unpack manpage for more details .

+2
source

unpack . / ( ).

( 32 ):

#!/usr/bin/perl

use strict;

my $strBuf = "perl rocks";
my $packed = pack("I Z15", length($strBuf), $strBuf);
{
    open(my $binFile, '>', "test.bin") || die("Error opening file\n");
    binmode $binFile;
    print $binFile $packed;
    close $binFile;
}


open(my $binFile, '<', "test.bin") || die("Error opening file\n");
binmode $binFile;

my $buffer;
read($binFile, $buffer, 4);  ## Read out unsigned int binary data
my $length    = unpack("I", $buffer);  ## Unpack the data

read($binFile, $buffer, $length);  ## Read the length out as binary
my $string = unpack("Z$length", $buffer);   ## Unpack the string data in buffer

print "Len: $length  String: $string\n";
exit;
+1
0

.

. int 2 , 4 8 ? ( .) -endian big-endian?

, .

The next problem is the exact format of the text string. Is it ASCII, EBCDIC or UTF format? Knowing this, you can calculate the length of the string and use one or more read operations to get a raw string, which you may need to convert to a more manageable form.

One more thing - you need to open the file in binary mode, otherwise you will not be able to get the expected results.

0
source

Source: https://habr.com/ru/post/1716725/


All Articles