5

I read how to calculate using the command line calculator and a HERE-document, but nevertheless I do not get what I expected and can not find my error, what I did in the shell was:

bc << HERE
>ibase=2
>obase=16
>1001
>HERE
100

I expected to get 9 as result since binary 1001 is hexadecimal 9, but I got 100.

4

Because you set ibase=2 first, you need to use obase=10000:

$ echo 'ibase=2; obase=10000; 1001' | bc
9
6

Because you are setting the input base first, then when you set the output base, the 16 will be interpreted according to the input base (2). It appears that the 6 in 16 is simply interpreted is a binary 1 bit in this case, and so the output base gets set to binary 11 or decimal 3.

To work around this, you can set the output base before you set the input base:

echo 'obase=16; ibase=2; 1001' | bc
1

While you can always factor out declarations for [io]base= based on the current input radix, another thing you might do is use the explicit hex notation, which should work regardless of input base. Like this:

printf %s\\n ibase=2 obase=F 1001 | bc

...which prints...

9

You might find this can be especially useful if you ever get lost when setting input bases, because you can always get back to a simple base 10 as easily as:

ibase=A

This is standardized syntax as mandated by POSIX:

  • When either ibase or obase is assigned a single digit value from the list in Lexical Conventions in bc, the value shall be assumed in hexadecimal. (For example, ibase=A sets to base ten, regardless of the current ibase value.) Otherwise, the behavior is undefined when digits greater than or equal to the value of ibase appear in the input. Both ibase and obase shall have initial values of 10.

This is a historical convention which began with dc (for which, on some systems, bc is still little more than a front-end) and so...

echo 2i Fo 1001p|dc

...also prints...

9
0

Link: command-line calculations using bc | basically tech

NOTE: You should put first obase, then ibase.

So you need to use hex first to "break out" of binary mode.

me@pc:~$ bc << HERE
> obase=16
> ibase=2
> 1001
> HERE
9

me@pc:~$ bc << HERE
> obase=16
> ibase=2
> 1001
> 111
> 1111
> 11111111
> HERE
9
7
F
FF

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.