Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare a couple binary bytes in code?

Tags:

perl

I read a binary file and want to make sure that some specific bytes have some specific value. What's the most perl way of doing this?

my $blob = File::Slurp::read_file( 'blob.bin', {binmode=>'raw'} );
substr( $blob, 4, 4 ) == #equals what?

I want to test if bytes 5-8 equal 0x32 0x32 0x00 0x04. What should I compare the substr to?

like image 547
Anna Avatar asked Nov 16 '25 00:11

Anna


1 Answers

substr( $blob, 4, 4 ) eq "\x32\x32\x00\x04"

If it's a 32-bit unsigned number, you might prefer the following:

unpack( "L>", substr( $blob, 4, 4 ) ) == 0x32320004   # Big endian
unpack( "L<", substr( $blob, 4, 4 ) ) == 0x04003232   # Little endian
unpack( "L",  substr( $blob, 4, 4 ) ) == ...          # Native endian

unpack( "N",  substr( $blob, 4, 4 ) ) == 0x32320004   # Big endian
unpack( "V",  substr( $blob, 4, 4 ) ) == 0x04003232   # Little endian

(Use l instead oaf L for signed 32-bit ints.)

substr can even be avoided when using unpack.

unpack( "x4 N", $blob ) == 0x32320004

You could also use a regex match.

$blob =~ /^.{4}\x32\x32\x00\x04/s

$blob =~ /^ .{4} \x32\x32\x00\x04 /sx

my $packed = pack( "N", 0x32320004 );
$blob =~ /^ .{4} \Q$packed\E /sx
like image 150
ikegami Avatar answered Nov 18 '25 20:11

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!