[CentOS] [OT] GNU bc base conversion

Warren Young wyml at etr-usa.com
Mon Aug 31 18:16:58 UTC 2015


On Aug 31, 2015, at 11:54 AM, Mike - st257 <silvertip257 at gmail.com> wrote:
> 
> define stanzas don't
> replicate the behavior as seen when used via piping or interactively. :-/

Again, it comes down to order of evaluation.  You can look at the following in three stages:

   define bin_to_hex(b) { obase=16; ibase=2; return b; }
   bin_to_hex(10101011)

1. Here is a number, 10101011, which you shall interpret in base 10, since that’s the default and no one has said otherwise yet.

2. Pass that value to bin_to_hex()

3. Change the obase and ibase, then return the parameter with those new settings.

You are expecting that because the define line appears first that it affects what follows, but it doesn’t affect anything until you call it for the first time.

That’s clear.

What I *don’t* understand is why this doesn’t work:

   define bin_to_hex(b) { obase=16; ibase=2; return b; }
   bin_to_hex(0)    /* bogus call to force obase and ibase */
   bin_to_hex(10101011)

For some strange reason, I get 20100 out of this with both GNU and BSD bc, even though ibase=2 and obase=10 by the time of the second bin_to_hex() call.

(If you’re confused about obase=10, realize that 10-base-16 is 16-base-10. :) )

Bottom line, don’t use bc for this kind of thing.  It’s not the right tool for the job.


More information about the CentOS mailing list