繁体   English   中英

如何在Perl中创建二进制文件?

[英]How to create binary file in Perl?

od -x test显示:

0000000 457f 464c 0102 0001

现在我想使用Perl来创建这样的文件。

open FH,'>','test_1';
#syswrite(FH,0x457f464c01020001); # not work
print FH 0x457f464c01020001;      # not work

如何在Perl中创建二进制文件?

要创建二进制文件,请使用

open (my $fh, '>:raw', $qfn)

放置

45 7f 46 4c 01 02 00 01

在该文件中,可以使用以下任何一种方法:

# Starting with a string of those bytes.
print $fh "\x45\x7f\x46\x4c\x01\x02\x00\x01";

# Starting with a hex representation of the file.
print $fh pack('H*', '457f464c01020001');

# Starting with the bytes.
print $fh map chr, 0x45, 0x7f, 0x46, 0x4c, 0x01, 0x02, 0x00, 0x01;

# Starting with the bytes.
print $fh pack('C*', 0x45, 0x7f, 0x46, 0x4c, 0x01, 0x02, 0x00, 0x01);
open(my $out, '>:raw', 'test_1.bin') or die "Unable to open: $!";
print $out pack('s<',255) ;
close($out);

你也可以在这里查看perl pack函数

print FH pack 'H*', '457f464c01020001'

print FH "\\x45\\x7f\\x46\\x4c\\x01\\x02\\x00\\x01"是另一种方式。 有关字符串中可用的转义序列的更多信息,请参阅perlop中的引用和引用类操作符 \\x工作方式与在C中的工作方式类似......除了Perl的扩展语法超出了\\xff

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM