Perl:如何将大端转换为小端

标签 perl endianness

这个问题解决了。非常感谢大家^^

我的问题和我正在使用的解决方案如下所述。

原始问题:--- 2013-05-08 编辑

我知道我可以像这样用 C++ 完成这个任务:

struct {              /* File Header */
    int a;
    int b;
    short c;    
    short d;
} PPPhdr;
PPPhdr head;
fstream fst;
fst.open("file.txt", ios_base::in|ios_base::binary);
fst.read((char*)&head, sizeof(PPPhdr));
SwapInt32(&(head.a));
SwapInt32(&(head.b));
SwapShort(&(head.c));
SwapShort(&(head.d));

所以,基本上 SwapInt32 会这样做:

0x89346512 -> 0x12653489

SwapShort 会这样做:

0x3487 -> 0x8734

现在我的问题是,如何在 Perl 中执行此操作?

我的方式:

open FH, "<file.txt" or die print "Cannot open file\n";
binmode FH;
read FH, $temp, 12;
($a,$b) = unpack("N2", substr($temp,0,8));
($c,$d) = unpack("n2", substr($temp,8,4));
close(FH);
print "$a\n$b\n$c\n$d\n";

最佳答案

你说你的数据是 big-endian,但你在 unpack 调用中使用了 i 模板(一个带符号的整数值)。您应该使用 N(一个无符号的 32 位大端数字)。您可能想阅读 documentation .

关于Perl:如何将大端转换为小端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16422677/

相关文章:

c++ - Wireshark 插件 : Is There a non-ntoh Version of tvb_get_ntoh64?

c - 小端与大端

perl - Perl 中的异步编程

perl - B::Lint 和 Perl::Critic 用于静态代码分析

arrays - 处理输入数据时获取 "The second parameter of split is a string, not an array"

perl - 使用最新版本的 Perl 为旧版本编写脚本

linux - 在 ssh 断开连接后保持 perl 脚本运行

c - 如何为可移植程序正确使用 gcc -fsso-struct?

endianness - 大端与小端机器

struct - 确保 D rawRead() 是文件中的大端结构