且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我怎样才能在Perl中总结大的十六进制值?

更新时间:2023-02-04 22:44:41

之前, 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)'