GNU bc Hacks

The GNU basic calculator is an extremely useful arbitrary precision calculator, but with several quirks. Like:

  • it doesn’t like lowercase hex numbers,
  • it doesn’t understand the 0xhex notation,
  • if input base is decimal 10, a-f are still treated as shorthands for decimal 10-15 (great!)
  • if input and output bases are N, any digit N through A-F saturates to N-1.

Some hacks available on the net try to fix these:

I have modified both the hacks and put them together:

  • bc will understand lowercase hex numbers (when ibase is 0x10), but when an expression starts with lowercase [a-f], it will not be evaluated as a hex number. So, 1e is the decimal number 30, but e1 is a variable.
  • 0xhex is understood to be a hex number, whatever the ibase, and this can be combined with numbers in decimal format. For example, when ibase is A, 100+0x100 will yield 356. When obase is 0x10, the output is 0x164.
  • 0bBinaryNumber is understood as a binary number. So, ibase is A, 0x10 + 0b100 will yield 20. I added a new flex rule to parse binary digits, but it doesn’t recognize the binary point yet, and will be ignored if t ed.
  • If obase is F+1 (decimal 16), outputs are printed with a leading 0x.
  • If obase is 2, outputs are printed with a leading 0b.

These are possible:

obase=0x10

sets output base to hex

obase=A

sets output base to decimal (standard bc behaviour)

obase=a

gives Runtime warning (func=(main), adr=4): obase too small, set to 2 because the variable a has the default value of zero.

Here is the stuff (with source and Windows binary compiled with gcc/MSYS and configured with the GNU readline library linked statically, so up/down keys will scroll through the command history). You need to have MSYS or Cygwin setup for a Windows build.

Here is the patch.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s