[CentOS] [OT] GNU bc base conversion

Mon Aug 31 12:55:11 UTC 2015
Mike - st257 <silvertip257 at gmail.com>

On Fri, Aug 28, 2015 at 4:14 PM, Warren Young <wyml at etr-usa.com> wrote:

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

Thanks Gordon.
Big bummer given that behavior. :-/
I had (and did test) definitions for other conversions (though I didn't
post them), but this one also drives it home.

~]$ grep bin_to_hex ~/.bcrc
define bin_to_hex(b) { obase=16; ibase=2; return b; }

~]$ echo "bin_to_hex(10101011)" | bc
9A2113
# so we're sending in a string with implied base10 ... sure enough matches
what BC errantly decided to do
~]$ echo "obase=16; 10101011" | bc
9A2113

~]$ echo "obase=16; ibase=2; 10101011" | bc
AB


>
> 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
>
>
Thanks Warren.
The order of obase and ibase definitely are bizarre and tripped me up the
first time around. I expected I should set ibase first and no no no that
was not the case! ;-)


To all:
I suppose my only options for this are to use shell functions or write a
script using a language that handles things properly (sanely?).


Thanks for the input everyone!

Best,
-- 
---~~.~~---
Mike
//  SilverTip257  //