如何比较代码中的几个二进制字节?
How to compare a couple binary bytes in code?
我读取了一个二进制文件并想确保某些特定字节具有某些特定值。执行此操作的最佳方式是什么?
my $blob = File::Slurp::read_file( 'blob.bin', {binmode=>'raw'} );
substr( $blob, 4, 4 ) == #equals what?
我想测试字节 5-8 是否等于 0x32 0x32 0x00 0x04
。我应该将 substr 与什么进行比较?
substr( $blob, 4, 4 ) eq "\x32\x32\x00\x04"
如果是 32 位无符号数,您可能更喜欢以下内容:
unpack( "N", substr( $blob, 4, 4 ) ) == 0x32320004 # Big endian
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
(对于带符号的 32 位整数,使用 l
而不是 oaf L
。)
使用 unpack
. 甚至可以避免 substr
unpack( "x4 N", $blob ) == 0x32320004
您也可以使用正则表达式匹配。
$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
我读取了一个二进制文件并想确保某些特定字节具有某些特定值。执行此操作的最佳方式是什么?
my $blob = File::Slurp::read_file( 'blob.bin', {binmode=>'raw'} );
substr( $blob, 4, 4 ) == #equals what?
我想测试字节 5-8 是否等于 0x32 0x32 0x00 0x04
。我应该将 substr 与什么进行比较?
substr( $blob, 4, 4 ) eq "\x32\x32\x00\x04"
如果是 32 位无符号数,您可能更喜欢以下内容:
unpack( "N", substr( $blob, 4, 4 ) ) == 0x32320004 # Big endian
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
(对于带符号的 32 位整数,使用 l
而不是 oaf L
。)
unpack
. 甚至可以避免 substr
unpack( "x4 N", $blob ) == 0x32320004
您也可以使用正则表达式匹配。
$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