How can I sum large hexadecimal values in Perl?

checksum, hex, perl

Solution

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)'

Problem

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 ```

Original source