Reading a binary file in parts

Is there a way I can read a binary without saving it as an array?

I have a very large binary that I need to read in half. And saving it as an array takes a lot of time, so I want to prevent this. I don’t care what happened to the file.

$size = stat($args{file});
my $vector;
open BIN, "<$args{file}";
read(BIN, $vector, $size->[7], 0);
close BIN;

# The code below is the part that takes a lot of time.
my @unpacked = split //, (unpack "B*", $vector);
return @unpacked;
+4
source share
2 answers

Read 1 byte at a time in the file using a special variable $/, and then use bitwise operators to check each bit in the byte. You should get something like the following:

$/ = \1; # read 1 byte at a time
while(<>) {
    my $ord = ord($_);

    # for each bit in the byte
    for(1 .. 8) {
        if($ord & 1) {
            # do 1 stuff
        }
        else {
            # do 0 stuff
        }

        # move onto the next bit
        $ord >>= 1;
    }
}
+1
source

vec, Perl .

0

All Articles