与 perl 交换字节 [英] byte swap with perl

查看:43
本文介绍了与 perl 交换字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取一个文件,其中包含使用33441122"字节顺序的整数.如何将文件转换为11223344"(大端)字节顺序?我尝试了一些东西,但我真的很迷茫.

I am reading a file, containing integers using the "33441122" byte order. How can I convert the file to the "11223344" (big endian) byte order? I have tried a few things, but I am really lost.

我已经阅读了很多关于 Perl 的文章,但是当谈到交换字节时,我一无所知.我该如何转换:

I have read a lot about Perl, but when it comes to swapping bytes, I'm in the dark. How can I convert this:

33 44 11 22

进入这个:

11 22 33 44

使用 Perl.

任何输入将不胜感激:)

Any input would be greatly appreciated :)

推荐答案

你可以一次读取 4 个字节,将其拆分为单个字节,交换它们并再次写出

You can read 4 bytes at a time, split it into individual bytes, swap them and write them out again

#! /usr/bin/perl

use strict;
use warnings;

open(my $fin, '<', $ARGV[0]) or die "Cannot open $ARGV[0]: $!";
binmode($fin);
open(my $fout, '>', $ARGV[1]) or die "Cannot create $ARGV[1]: $!";
binmode($fout);

my $hexin;
my $n;
while (($n = read($fin, $bytes_in, 4)) == 4) {
    my @c = split('', $bytes_in);
    my $bytes_out = join('', $c[2], $c[3], $c[0], $c[1]);
    print $fout $bytes_out;
}

if ($n > 0) {
    print $fout $bytes_in;
}

close($fout);
close($fin);

这将在命令行上调用为

perl script.pl infile.bin outfile.bin

outfile.bin 将被覆盖.

这篇关于与 perl 交换字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆