Perl: Reading binary file one byte at a time

13,891

read returns the byte as the char "\x50", not the number 0x50. Change the printf line to

printf "0x%04X\t0x%02X\n", $offset, ord $oneByte;

Another option is to use unpack 'c', $oneByte.

Share:
13,891
DarkMorford
Author by

DarkMorford

Updated on August 09, 2022

Comments

  • DarkMorford
    DarkMorford over 1 year

    I'm writing a tool that needs to read a binary file one byte at a time, process each byte, and potentially take some action depending on the processed value. But for some reason the values Perl is getting are not the same as the data in the file. I'm using code similar to this (stripped down for brevity, but this still exhibits the issue):

    #!/usr/bin/perl
    use strict;
    
    my $bytesToProcess = 16;
    my $fileName = 'datafile.bin';
    
    print "Processing $bytesToProcess bytes...\n";
    
    open FILE, "<:raw", $fileName or die "Couldn't open $fileName!";
    
    for my $offset (0 .. $bytesToProcess - 1)
    {
        my $oneByte;
        read(FILE, $oneByte, 1) or die "Error reading $fileName!";
        printf "0x%04X\t0x%02X\n", $offset, $oneByte;
    }
    
    close FILE;
    

    Input values (first 16 bytes of data file): 50 53 4D 46 30 30 31 35 00 00 70 00 07 3F 10 00

    Output:

    Processing 16 bytes...
    0x0000  0x00
    0x0001  0x00
    0x0002  0x00
    0x0003  0x00
    0x0004  0x00
    0x0005  0x00
    0x0006  0x01
    0x0007  0x05
    0x0008  0x00
    0x0009  0x00
    0x000A  0x00
    0x000B  0x00
    0x000C  0x00
    0x000D  0x00
    0x000E  0x00
    0x000F  0x00
    

    Any idea what's going wrong here?