LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   bc: inconsistent result (https://www.linuxquestions.org/questions/linux-newbie-8/bc-inconsistent-result-4175599746/)

fanoflq 02-14-2017 12:13 PM

bc: inconsistent result
 
Using bc utility to convert between binary and decimals.

Code:

Decimal to binary: 
#default input base is 10.
~ $ echo "ibase=10;obase=2;254;" | bc        #Convert 254 decimal to binary
11111110

~ $ echo "obase=2;ibase=10;254;" | bc
11111110

#Decimal-to-Binary, INPUT arguments order
does not matter, but for
Binary-To-Decimal, order matters
for INPUT arguments! See below.

Binary to decimal: 
~ $ echo "obase=10;ibase=2;1111;" | bc           
15                #Correct output

# Input order matters. 
Example incorrect output due to input order

~ $ echo "ibase=2;obase=10;1111;" | bc       
1111                        # incorrect output

Did I missed anything?
Why does order matter in one case, and not the other?

Is there a utility that converts IP4 address (dot decimal notation) into "dot" binary outputs?

Thank you.

hydrurga 02-14-2017 12:19 PM

http://stackoverflow.com/questions/9...-obase-options

fanoflq 02-14-2017 01:55 PM

Quote:

Originally Posted by hydrurga (Post 5670457)

Thank you.
From link above:
"For multi-digit numbers, bc changes all input digits greater or equal to ibase to the value of ibase-1. "

Here I an example where all the digits are less than ibase.
Thus none of the input digits of obase or
input values (011 or 0111) exceeded ibase's value.
Thus there is no change to the input digits.
But the answers are still incorrect.

Code:

~ $ echo "ibase=2;obase=10;011" | bc
11          #I should get 3 decimal.
~ $ echo "ibase=2;obase=10;0111" | bc
111        #I should get 7 decimal.

What did I missed?

suicidaleggroll 02-14-2017 02:01 PM

You missed the line right above that one:
Quote:

As soon as ibase=6 is interpreted, numbers are read in base 6.
This
Code:

$ echo "ibase=2;obase=10;011" | bc
11          #I should get 3 decimal.

is not correct. As soon as ibase is interpreted, ALL numbers are read in base 2. That includes your "obase". So while you think you're setting obase to ten, you're setting it to binary "10", which is 2. You would need to set obase to ten base 2, or "1010", for it to be interpreted correctly in this order:
Code:

$ echo "ibase=2;obase=1010;011" | bc
3
$ echo "ibase=2;obase=1010;0111" | bc
7
$ echo "ibase=2;obase=1010;1111" | bc
15


fanoflq 02-14-2017 02:06 PM

Thank you.


All times are GMT -5. The time now is 12:30 PM.