我想使用Perl将某些数据转换为二进制。数据需要以8位二进制输出。原始数据采用以下格式:
137.0000
136.0000
133.0000
136.0000
10.0000
134.0000
0.0000
132.0000
132.0000
为此,我转换了数据以抑制“ .0000”,然后使用pack
带有该选项的函数C*
(根据文档,此格式对应于“无符号字符(通常为8位)”)。我称这个文件为txt2bin.pl
:
my $file = $ARGV[0];
my $fileout = $file.".bin";
if($file eq "-h" or $file eq "-help" or $file eq "")
{
print "Usage : txt2bin.pl file_in\n";
print " file_out = file_in.bin\n";
print "This script converts a txt file to a binary file\n";
}
else
{
print "File in = $file\n";
print "File out = $fileout\n";
open(FILE,"<$file") or die $!;
open(FILEOUT,">$fileout") or die $!;
binmode FILEOUT;
while(defined(my $line=<FILE>))
{
chomp($line);
$line =~ s/\.0000//;
syswrite FILEOUT, pack("C*",$line);
}
close(FILE);
close(FILEOUT);
}
我还需要能够执行反向操作,因此,我创建了另一个文件bin2txt.pl
:
my $file = $ARGV[0];
my $fileout = $file.".txt";
if($file eq "-h" or $file eq "-help" or $file eq "")
{
print "Usage : bin2txt.pl file_in\n";
print " file_out = file_in.txt\n";
print "This script converts a binairy file to a txt file\n";
}
else
{
print "File in = $file\n";
print "File out = $fileout\n";
my $file = "<$file";
# undef $/ to read whole file in one go
undef $/;
open(FILE,$file) or die $!;
open(FILEOUT,">$fileout") or die $!;
# binmode FILE to supress conversion of line endings
binmode FILE;
my $data = <FILE>;
$data =~ s/(.{1})/unpack("C*",$1).".0000 \n"/eg;
syswrite FILEOUT, $data;
}
但是,当我执行第一个程序txt2bin.pl
,然后执行第二个程序时,我应该得到:
137.0000
136.0000
133.0000
136.0000
10.0000
134.0000
0.0000
132.0000
132.0000
相反,我得到了这个:
137.0000
136.0000
133.0000
136.0000
134.0000
0.0000
132.0000
132.0000
在10.0000
不露面,难道你们对此有任何想法?感谢您的帮助。
您需要将s
修饰符添加到regexp替换中,以匹配10(换行符):
$data =~ s/(.{1})/unpack("C*",$1).".0000 \n"/seg;
s
将字符串视为单行。即,更改“。” 匹配任何字符,即使是换行符,通常不会匹配。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句