简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM