我怎样才能在Perl中总结大的十六进制值? [英] How can I sum large hexadecimal values in Perl?

查看:685
本文介绍了我怎样才能在Perl中总结大的十六进制值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遍历一组32位十六进制字符串(DEADBEEF,12345678等),我试图将它们汇总在一起形成一个32位校验和。假设在下面的例子中变量 $ temp 加载了一些十六进制字符串。

  my $ temp; 
我的$校验和;

(...)
{
#assume $ temp在这里加载一个新的十六进制字符串
my $ tempNum = hex($ temp);
$ checksum + = $ tempNum;
$ checksum& = 0xFFFFFFFF;
print printf(checksum:%08X,$ checksum);
}

前几个值是7800798C,44444444和44444444 。输出是:


校验码:7800798C
校验码:
BC44BDD0
校验码:FFFFFFFF

checksum:FFFFFFFF


etc ..

as你可以看到前两个总和是正确的,然后它似乎饱和。我缺少一些关于Perl变量大小限制的信息吗?



编辑:这是脚本的实际输出(字符串是十六进制字符串,值是该字符串的十进制转换,校验和是结果输出):

 
字符串:7800798C,值:2013297036,校验和7800798C
字符串44444444值1145324612校验和BC44BDD0
字符串44444444值1145324612校验和FFFFFFFF
字符串44444444值1145324612校验和FFFFFFFF
字符串78007980,值:2013297024,校验和FFFFFFFF
字符串:44444444,值:1145324612,校验和FFFFFFFF


解决方案

之前, Perl Monks 提出了这个问题。



答案似乎是使用整数



请参阅原文答案Perl Monks和 perldoc integer

  $ perl -we'use integer; printf(%08X\\\
,0xFFFF_FFFF + 0xFFFF_FFFF)'


I'm iterating over a set of 32-bit hexadecimal strings ("DEADBEEF", "12345678", etc..) and I'm trying to sum them together to form a 32-bit checksum. Assume that the variable $temp is loaded with some hexadecimal string in the example below.

my $temp;
my $checksum;

for (...)
{
    #assume $temp is loaded with a new hex string here
    my $tempNum = hex ($temp);
    $checksum += $tempNum;
    $checksum &= 0xFFFFFFFF;
    print printf("checksum: %08X",$checksum);
}

The first few values are "7800798C", "44444444", and "44444444". The output is:

checksum: 7800798C
checksum: BC44BDD0
checksum: FFFFFFFF
checksum: FFFFFFFF

etc..

as you can see the first two summations are correct and then it seems to saturate. Am I missing something regarding the size limit of Perl variables?

EDIT: This is the actual output from the script (string is the hex string, value is the decimal conversion of that string, and checksum is the resulting output):

string: 7800798C, value: 2013297036, checksum 7800798C
string: 44444444, value: 1145324612, checksum BC44BDD0
string: 44444444, value: 1145324612, checksum FFFFFFFF
string: 44444444, value: 1145324612, checksum FFFFFFFF
string: 78007980, value: 2013297024, checksum FFFFFFFF
string: 44444444, value: 1145324612, checksum FFFFFFFF

解决方案

This was asked at Perl Monks before.

The answer seems to be "use integer".

Please see the original answer at Perl Monks and perldoc integer.

$ perl -we 'use integer; printf("%08X\n",  0xFFFF_FFFF + 0xFFFF_FFFF)'

这篇关于我怎样才能在Perl中总结大的十六进制值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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