Hello CentOS List Members, 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. No doubt the syntax is in some way wrong, but when I test from the CLI and the right values are returned, I have to wonder. Other than a few other define statements, the only other option I have set is scale=5 in my bcrc. In reference to the order of (o|i)base parameters, I have specified obase before ibase [0]. [0] http://docstore.mik.ua/orelly/unix/upt/ch49_03.htm See below for my examples. Thanks! ]$ echo "bin_to_dec(1001)" | bc 1001 # should be decimal 9 ]$ echo "obase=10; ibase=2; 1001" | bc 9 ]$ grep bin_to_dec ~/.bcrc define bin_to_dec(b) { obase=10; ibase=2; return b; } ---- ]$ echo "hex_to_dec(AB)" | bc 99 # should be decimal 171 ]$ echo "obase=10; ibase=16; AB" | bc 171 ]$ echo "obase=A; ibase=16; AB" | bc 171 ]$ grep hex_to_dec ~/.bcrc define hex_to_dec(h) { obase=A; ibase=16; return h; } -- ---~~.~~--- Mike // SilverTip257 //
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.
On Aug 28, 2015, at 9:50 AM, Gordon Messmer <gordon.messmer at gmail.com> wrote:> > 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.Yes, and it?s a serious design mistake in bc, IMHO. No other programmable system I?ve ever used changes how numbers in program text are interpreted based on prior commands to the system. I wrote a long answer explaining this on the Unix & Linux Stack Exchange here: http://unix.stackexchange.com/a/199620