Perl将short转换为一个字节

时间:2014-05-27 10:13:06

标签: perl byte short

有谁知道如何将两个字节从文件转换为一个字节? 我试图将两个字节读入数组的每个元素,然后将其除以6553,将时间除以255,以转换为一个字节。然而,这不起作用。 有什么建议吗?

open my $fh, '<:raw', $test;
my @info = do {
    local $/ = \2;
    <$fh>;
};
close($fh);

foreach(@info){
    $_= (($_)/65535)*255;
}
my $temp = "temp.txt";

open(TEMP, ">", $temp);
print TEMP my $info;
close(TEMP);

错误:

Argument "\0^B" isn't numeric in division (/) at ./con.pl line 33.
Argument "^A^B" isn't numeric in division (/) at ./con.pl line 33.
Argument "^B^B" isn't numeric in division (/) at ./con.pl line 33.
Argument "^E^B" isn't numeric in division (/) at ./con.pl line 33.
Argument "^G^B" isn't numeric in division (/) at ./con.pl line 33.
Argument "^H^B" isn't numeric in division (/) at ./con.pl line 33.
Argument "^G^B" isn't numeric in division (/) at ./con.pl line 33.

2 个答案:

答案 0 :(得分:1)

如果字节来自文件,请将它们转换为数字。这就是unpack的用途:

$c = "\x1\x2";
print unpack 'n', $c;

输出:258

使用pack将数字转换回字节。

答案 1 :(得分:0)

pack 'C', unpack 'n', $twobytes;            # Big-endian input
pack 'C', unpack 'v', $twobytes;            # Little-endian input
pack 'C*', unpack 'n*', $many_byte_pairs;   # Big-endian input
pack 'C*', unpack 'v*', $many_byte_pairs;   # Little-endian input

检查是否有溢出。