Perl: reading a binary one byte at a time

I am writing a tool that should read a binary file one byte at a time, process each byte, and possibly take some actions depending on the value being processed. But for some reason, Perl values ​​do not get the same as the data in the file. I am using code like this (shortened for brevity, but it still matters):

#!/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 the data file): 50 53 4D 46 30 30 31 35 00 00 70 00 07 3F 10 00

Conclusion:

 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 is going wrong here?

+6
source share
1 answer

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

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

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

+8
source

All Articles