2

我正在尝试使用以下代码从二进制文件中读取前 4 个字节(应该是一个 uint32_t 指示文件头大小):

 sysopen(my $inHandle, $fileName, O_RDONLY | O_BINARY) 
     or croak("Failed to open file $fileName");
 die if(read($inHandle, my $currDword, 4) != 4);
 printf("length is %d\n", $currDword);

它给了我

Argument "M-\f^B" isn't numeric in printf at sbin.pl line 12.
length is 0

我搞砸了什么吗?perl 还会自动处理字节序(二进制是小字节序),还是有其他方法来获取字节?谢谢!

4

1 回答 1

9

您需要将四个字节转换为一个数字。假设它是一个无符号整数,以下两个将根据字节的顺序执行:

my $hsize = unpack('N',  $currDword);  # Big-endian    12 34 56 78 => 0x12345678
my $hsize = unpack('L>', $currDword);  # Big-endian    12 34 56 78 => 0x12345678
my $hsize = unpack('V',  $currDword);  # Little-endian 12 34 56 78 => 0x78563412
my $hsize = unpack('L<', $currDword);  # Little-endian 12 34 56 78 => 0x78563412
于 2013-06-26T18:36:12.770 回答