shelldc

Change input base in shell script with dc?


I'm trying to change the input and the output base using dc in a shell script. I'm having trouble writing down the exact command. I do not have BASH.

I've tried variations on this: (input numb) 2i 10o p | dc


Solution

  • The dc man page uses the term "radix", not "base"; that might help you search for information.

    You have to set the input radix before giving it an input number. For example:

    echo 100 2i p | dc
    

    prints 100 (decimal) because the radix was still set to the default 10 (decimal) when dc saw the input value 100.

    Try this:

    echo 16i DEADBEEF 10o p 2o p | dc # but see below
    

    The output is:

    DEADBEEF
    11011110101011011011111011101111
    

    Note that dc seems to require upper case for the hex digits A .. F. And you have to be careful with radix specifications; after you've done 16i to set input to hexadecimal, 10i interprets 10 as a hexadecimal number and sets the input radix to 16 (and 16i tries to set it to 0x16 or 22, which is illegal).

    In fact, I see I ran into that problem myself. I meant to set the output radix to 16. I should have written Ao p 2o p rather than 10o p 2o p. I'll leave it as it is to illustrate the issue.