23

I've been using bc to convert numbers between binary to hex, octal to decimal and others.

In the following example, I was trying to convert base 16 (hex) number to binary, octal and decimal.

I don't have any problem with the first 2 attempts.

$ echo 'ibase=16; obase=2; FF' | bc  
11111111
$ echo 'ibase=16; obase=8; FF' | bc 
377

But when I tried to convert base 16 (hex) number to base 10 (decimal), I was getting wrong answer. The answer should be 255

$ echo 'ibase=16; obase=10; FF' | bc 
FF
2
  • 1
    For numbers smaller than a machine word (32 or 64 bits) in bash, you don't need bc: printf '%d\n' 0x$hex or just echo $(( 0x$hex )) Aug 26, 2018 at 0:54
  • See the linked duplicate, specifically this in the accepted answer:"If you give ibase first instead, it changes the interpretation of the following obase setting" Aug 27, 2018 at 0:39

1 Answer 1

65

Once ibase=16 is done, further input numbers are in hexadecimal, including 10 in obase=10 which represents the decimal value 16. So either set obase before, or set it after, using the new input base (now hexadecimal):

$ echo 'obase=10; ibase=16; FF' | bc
255
$ echo 'ibase=16; obase=A; FF' | bc
255
2
  • 14
    Theorem: Every multiplicative base written in itself is 10.
    – Joshua
    Aug 26, 2018 at 4:17
  • 8
    @Joshua, yea, that's pretty much the definition, I think.
    – ilkkachu
    Aug 26, 2018 at 9:57