Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear PerlMonks,
I am trying to convert 32 bit binary number to Hex
Here is the code:
use strict; use warnings; my $bin_val; my $dec_val; my @temp_reference_value = ("11111111111111111111111111111111", "11111 +11111111111111111111111111"); for(my $i=0; $i<=$#temp_reference_value; $i++ ) { $dec_val = oct("$temp_reference_value[$i]"); $bin_val = sprintf('0x%x', $dec_val) if($dec_val); print "Bin value $temp_reference_value[$i] and Hex value is $bin_v +al \n"; }
The error message that i am receiving is
Integer overflow in octal number at bintohex.pl line 11. Octal number > 037777777777 non-portable at bintohex.pl line 11. Bin value 11111111111111111111111111111111 and Hex value is 0xffffffff Integer overflow in octal number at bintohex.pl line 11. Octal number > 037777777777 non-portable at bintohex.pl line 11. Bin value 1111111111111111111111111111111 and Hex value is 0xffffffff
Hence request your inputs in resolving this issue.

Replies are listed 'Best First'.
Re: Integer overflow in octal number
by JavaFan (Canon) on May 05, 2009 at 11:40 UTC
    The overflow warning comes from the fact that you are using "11111111111111111111111111111111" as an octal number. "11111111111111111111111111111111" octal is not a 32-bit number. It's a 96-bit number. Hence the overflow. If you want a 32-bit number, write it as: 0b11111111111111111111111111111111.
    $ perl -wE 'say 0b11111111111111111111111111111111' 4294967295
Re: Integer overflow in octal number
by irah (Pilgrim) on May 05, 2009 at 11:50 UTC

    When you pass the argument for oct function, you have to specify the type of that number. Whether, it is octal, binary.

    my @temp_reference_value = ("0b11111111111111111111111111111111", "0b1 +1111111111111111111111111111111");

    change your line to above code and check it. It will work. By default, the argument take it as, octal. The highest octal number in 32 bit machine is, 037777777777. So the error was came.

      Hi that worked perfectly. Thanks a lot Monks.
Re: Integer overflow in octal number
by vinoth.ree (Monsignor) on May 05, 2009 at 11:37 UTC
Re: Integer overflow in octal number
by Marshall (Canon) on May 05, 2009 at 18:19 UTC
    I think we've got the overflow problem solved. I'd just like to make a suggestion re: loop conditions.
    my @temp_reference_value = ("111", "11111111"); for(my $i=0; $i<=$#temp_reference_value; $i++ ) { ... use $temp_reference_value[$i] here ... }
    is not the Perl way of doing things. One of the magic things about Perl is that @var knows how big it is and there are better iterators than this C style for loop!
    foreach my $value (@temp_reference_value) { .. use unsubsripted $value here ... .."off by one" won't happen... a big advantage! }
    Is a more Perl way of doing things!