Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Power of a power in bash with bc

Tags:

bash

math

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?

like image 876
monkeyUser Avatar asked Jan 27 '23 22:01

monkeyUser


1 Answers

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
like image 163
Benjamin W. Avatar answered Feb 06 '23 18:02

Benjamin W.