0

I have a problem in interpreting the bytes from binary file in perl.

Snippet of the code :

open IMG_FH, $IMAGE_FILE or die $!;
binmode IMG_FH;

sysread(IMG_FH, $Var_Options, 2);

if ($Var_Options == 0)
{
    print "Received 0\n";
}
elsif ($Var_Options == 28)
{
    print "Received 0\n";
}
else
{
    print "Error\n";
}

Even though I am sure that the word kept at the start of the binary file is : "001c" (Hexadecimal), I am ending up printing "Error";

Please help.

1 Answer 1

1

You're using the wrong tools if you're analyzing binary data.

Instead of doing a simple numeric equality test, you need to study pack, unpack, and the perlpacktut.

One very helpful tool is to use Data::Dump or the core library Data::Dumper.

I would rewrite your script to the following to inspect the first two bytes:

use strict;
use warnings;
use autodie;

my $file = 'test-all-the-things.jpg';

open my $fh, '<:raw', $file;

sysread $fh, my $data, 2;

use Data::Dump;
dd $data;

Outputs:

"\xFF\xD8"

This module adapts the output when one tries to analyze more than just 2 bytes:

sysread $fh, my $data, 20;

use Data::Dump;
dd $data;

Outputs:

pack("H*","ffd8ffe000104a46494600010101006000600000")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.