Search code examples
bashmathbc

Power of a power in bash with bc


I want to calculate this:

0x0404cb * 2**(8*(0x1b - 3))

which in decimal is:

263371*2^^(8*(27-3))

using | bc.

I tried with

echo 263371*2^^(8*(27-3)) | bc
expr 263371*2^^(8*(27-3)) | bc
zsh: no matches found: 263371*2^^(8*(27-3))

or try to resolve this

238348 * 2^176^

Can I resolve in one shot?


Solution

  • The bc "power of" operator is ^. You also have to quote everything to prevent the shell from trying to do things like history substitution and pathname expansion or interpreting parentheses as subhells:

    $ bc <<< '263371*2^(8*(27-3))'
    1653206561150525499452195696179626311675293455763937233695932416
    

    If you want to process your initial expression from scratch, you can use the ibase special variable to set input to hexadecimal and do some extra processing:

    eqn='0x0404cb * 2**(8*(0x1b - 3))'
    
    # Replace "**" with "^"
    eqn=${eqn//\*\*/^}
    
    # Remove all "0x" prefixes
    eqn=${eqn//0x}
    
    # Set ibase to 16 and uppercase the equation
    bc <<< "ibase = 16; ${eqn^^}"
    

    or, instead of with parameter expansion, more compact and less legible with (GNU) sed:

    sed 's/\*\*/^/g;s/0x//g;s/.*/\U&/;s/^/ibase = 16; /' <<< "$eqn" | bc