perl - 参数“xxx”在printf中不是数字

时间:2013-06-26 18:31:02

标签: perl

我正在尝试使用以下代码从二进制文件中读取前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也会自动处理字节序(二进制是小端),还是有其他方法来获取字节?谢谢!

1 个答案:

答案 0 :(得分: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