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

Hi I am trying to run 'bc' unix command within perl but that seems really hard right now. I am using bc because the numbers I am using are beyond 64bit in size. Here's a code snippet.
$temp_addr = "A5A5A5A5A5A5A5A5"; $temp_data = "82100000"; my $bc_addr = `echo \"ibase=16;obase=16;($temp_addr/8)\" | bc`; my $bc_data = `echo \"ibase=16;obase=16;($temp_data*200)\" | bc`; die "$bc_data, $bc_addr";
The output for the code when I run it is something like...

02 08 20 08 03 09 14 , 02 00 14 05 04 06 12 13 04 04 15 18 07 11 15 02 00

Now I was expecting the o/p in hex and a valid one at that. This one flies over my head. When I run bc in the shell directly things are just fine.

Replies are listed 'Best First'.
Re: bc within perl
by Athanasius (Cardinal) on Nov 08, 2016 at 09:22 UTC
      I did try BigInt prior to this. That has a restriction of 64bit binary and doesn't support beyond that. I am not sure on BigFloat nor BigRat. The numbers I have in mind are going to be at most 73bits and I couldn't find a better alternative to 'bc' so far.
        > That has a restriction of 64bit binary

        Are you sure?

        perl -Mbigint -wE 'say 12345678912345678912345678912345678912345678912 +3456789123456789 ** 1234'
Re: bc within perl
by hippo (Archbishop) on Nov 08, 2016 at 09:36 UTC

    This is not an error in perl. Re-writing your first command directly in the shell we see this:

    $ echo "ibase=16;obase=16;(A5A5A5A5A5A5A5A5/8)" | bc 05 06 01 09 10 06 00 00 05 16 14 07 14 20 $

    If this isn't the output you expect then you will need to dig deeper into usage of bc before wrapping it in anything else. I don't use it so can't comment further.

      Aah thanks. My bad. I changed it a bit. For some reason, obase variable should be defined first and then ibase. This is now fixed. Thank you for the help, monks :).

        For some reason, obase variable should be defined first and then ibase

        specifically, because you told it to output in base twenty-two.

        ibase=16; # set the input base to hexadecimal. # all numerical inputs will be treated with an # implied 0x prefix obase=16; # 16 is implied hexadecimal 0x16 = sixteen plus six = twe +nty-two (A5A5A5A5A5A5A5A5/8); # divide 0xA5... by 0x8, and output in base t +wenty-two

        And my copy of the bc manpage explains "For bases 2 through 16, the usual method of writing numbers is used. For bases greater than 16, bc uses a multi-character digit method of printing the numbers where each higher base digit is printed as a base 10 number. The multi-character digits are separated by spaces. ..."

        Sanity check: you expected 0x14b4b4b4b4b4b4b4, which is about (0x14) * 16**14, plus some change: 20 * 16**14 = 1.44e18, plus. You got "05 06 01 09 10 06 00 00 05 16 14 07 14 20", which is about 05 * 22**13, plus some change: 1.41e18, plus. Yep, the output was in base-22.