shell 進制轉換

shell 腳本默認數值是由10 進制數處理,除非這個數字某種特殊的標記法或前綴開頭. 纔可以表示其它進制類型數值。如:以 0 開頭就是 8 進制.以0x 開頭就是16 進制數.


使用方法:

  • 其它進制轉爲10進制

八進制轉十進制:

[chengmo@centos5 ~]$ ((num=0123));
[chengmo@centos5 ~]$ echo $num;
83

[chengmo@centos5 ~]$ ((num=8#123));
[chengmo@centos5 ~]$ echo $num;    
83

((表達式)),(())裏面可以是任意數據表達式。如果前面加入:”$”可以讀取計算結果。

十六進制轉十進制:

[chengmo@centos5 ~]$ ((num=0xff)); 
[chengmo@centos5 ~]$ echo $num;    
255
[chengmo@centos5 ~]$ ((num=16#ff));
[chengmo@centos5 ~]$ echo $num;    
255

base-32轉十進制:

[chengmo@centos5 ~]$ ((num=32#ffff));
[chengmo@centos5 ~]$ echo $num;      
507375

base64轉十進制:

[chengmo@centos5 ~]$ ((num=64#abc_)); 
[chengmo@centos5 ~]$ echo $num;       
2667327

二進制轉十進制

[chengmo@centos5 ~]$ ((num=2#11111111));  
[chengmo@centos5 ~]$ echo $num;
255

  • 十進制轉爲其它進制

十進制轉八進制

這裏使用到:bc外部命令完成。bc命令格式轉換爲:echo "obase=進制;值"|bc

[chengmo@centos5 ~]$ echo "obase=8;01234567"|bc
4553207

二進制,十六進制,base64轉換爲 十進制也相同方法。

[chengmo@centos5 ~]$ echo "obase=64;123456"|bc  
30 09 00

裏記得賦值時候用(())符號。不能直接用=號了。=號沒有值類型默認將後面變成字符串了

[chengmo@centos5 ~]$ num=0123;
[chengmo@centos5 ~]$ echo $num;
0123

0開頭已經失去了意義了。

可以通過定義符:let達到(()) 運算效果。

[chengmo@centos5 ~]$ let num=0123;
[chengmo@centos5 ~]$ echo $num;   
83


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章