bc 是 Linux 下的命令列式的計算器。 題目雖然叫任意進位制,但是因為 bc 的限制,輸入進位制是 2~16 範圍;輸出進位制是 2~999 範圍。這與常見計算器的進位制範圍是一致的,比如 windows 計算器最高也只能處理 16 進位制輸入資料。
一、 bc 計算器的使用

bc 計算器預設輸入、輸出都為 10 進位制。
[root@CentOS6 ~]# bc #開啓 bc 計算器
bc 1.06.95
Copyright 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty’.
88*123 #計算 88*123
10824 #計算器輸出結果
#
#
123+65*2-100 #計算 123+65*2-100
153 #計算器輸出結果

bc 計算器進位制轉換
[root@centos6 ~]# bc
obase=16 #設定輸出為 16 進位制
ibase=2 #設定輸入為 2 進位制
1111111111111100011010 #輸入 2 進位制數
3FFF1A #轉換為 16 進位制

二、通過管道運算與進位制轉換

這裏使用的管道可以簡單的理解為將 echo “1+2″ 傳送給 bc 計算器
[root@centos6 ~]# echo “1+1” | bc #將 1+1 傳送給 bc 計算器
2
[root@centos6 ~]#
[root@centos6 ~]# echo “5*10-1” | bc #將 5*10-1 傳送給 bc 計算器
49

雙引號、單引號、反單引號的使用
[root@centos6 ~]# echo “123+123” | bc
246
[root@centos6 ~]# echo ‘111+111’
111+111
[root@centos6 ~]# echo ‘111+111′ | bc
222
[root@centos6 ~]# echo `111+111` | bc
-bash: 111+111: command not found
[root@centos6 ~]# echo “`echo 123`+10” | bc
133

三、使用中遇到的問題

先設定 obase 在設定 ibase,計算器正常。
[root@centos6 ~]# bc
bc 1.06.95
Copyright 2006 Free Software Foundation,
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty’.
obase=16
ibase=2
1111111111111100011010
3FFF1A

先設定 ibase 在設定 obase,計算器輸出不正常。
[root@centos6 ~]# bc
bc 1.06.95
Copyright 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty’.
ibase=2
obase=16
1111111111111100011010
21220002012002

先設定 obase 在設定 ibase,計算輸出正常
修改 obase 後計算輸出不正常
[root@centos6 ~]# bc
bc 1.06.95
Copyright 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty’.
obase=16
ibase=2
1111111111111100011010
3FFF1A
obase=10
1111111111111100011010
1111111111111100011010

先設定 obase 在設定 ibase 正常,ibase 與 obase 互換輸出不正常。
[root@centos6 ~]# bc
bc 1.06.95
Copyright 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty’.
obase=16
ibase=2
1111111111111100011010
3FFF1A
obase=2
ibase=16
3FFF1A
1011010101

使用管道時同樣只能先給 obase 賦值
[root@centos6 ~]# echo “ibase=2;obase=16;11101” | bc
1002
[root@centos6 ~]# echo “obase=16;ibase=2;11101” | bc
1D

結論?????
在 bc 計算器中,obase 與 ibase 的賦值有先後順序。
且在計算過程中 ibase 與 obase 只能賦值一次。