[CentOS] [OT] GNU bc base conversion

Fri Aug 28 15:50:13 UTC 2015
Gordon Messmer <gordon.messmer at gmail.com>

On 08/28/2015 07:15 AM, Mike - st257 wrote:
> Thoughts as to why my BC functions aren't properly converting between bases?
>
> Decimal to binary or hex works fine, but not binary or hex to decimal and
> so forth.

I'm not an expert in bc, so I might be wrong, but it looks like setting 
the ibase inside a function is simply too late.  ibase affects how bc 
interprets input.  So "echo "bin_to_dec(1001)" | bc" is going to 
interpret the value of 1001 while reading it from input, not after 
passing it to a function where ibase is reset.

Supporting that theory:
$ bc
...
define bin_to_dec(b) { obase=10; ibase=2; return b; }
bin_to_dec(1001)
1001

Decimal to binary and hex work correctly because decimal input is the 
default.  Since ibase is already 10, those values are interpreted the 
way you want, but not because you're setting ibase in your function.