我有这样的文本文件:
float a[10] = {
7.100000e+000 ,
9.100000e+000 ,
2.100000e+000 ,
1.100000e+000 ,
8.200000e+000 ,
7.220000e+000 ,
7.220000e+000 ,
7.222000e+000 ,
1.120000e+000 ,
1.987600e+000
};
unsigned int col_ind[10] = {
1 ,
4 ,
3 ,
4 ,
5 ,
2 ,
3 ,
4 ,
1 ,
5
};
现在,我想将每个数组(float/unsigned int)转换为不同的二进制文件 - big endian类型,所有浮点值的二进制文件和所有整数值的二进制文件。
考虑到我在每个数组中有超过两个 millon 元素,在 Perl 中执行此操作的简单方法是什么?
最佳答案
您需要查看 binmode
和 pack
.这是一个可以帮助您入门的示例。我不确定我是否选择了您需要的包模板,但请参阅 pack
文档了解所有选择。
use strict;
use warnings;
my ($fh, $pack_template);
while (my $line = <>){
if ( $line =~ /(float|int)/ ){
$pack_template = $1 eq 'int' ? 'i' : 'f';
undef $fh;
open $fh, '>', "$1.dat" or die $!;
binmode $fh;
next;
}
next unless $line =~ /\d/;
$line =~ s/[,\s]+$//;
print $fh pack($pack_template, $line);
}
关于perl - 如何使用 Perl 将文本中的浮点值转换为二进制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2891904/