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
wjandrea
  • 658
  • 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 )) – dave_thompson_085 Aug 26 '18 at 00: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" – Sergiy Kolodyazhnyy Aug 27 '18 at 00:39

1 Answers1

64

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
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
A.B
  • 36,364
  • 2
  • 73
  • 118