bash, hex, decimal, printf, bc
網路上很多教學是使用bc函數,但不是每台電腦都有裝這個套件
而造成轉換失敗,得到非預期的結果
因此這裡使用bash內建的printf函數做轉換
第一個參數寫出要轉換的單位(%d, %x or %X),第二個參數寫出要轉換的數字甚至字串也可以
#!/bin/bash
# decimal(32) to hex(0x20)
dec_num="32"
printf "%02X\n" "$dec_num"
# hex(0x20) to decimal(32), and assign to a variable
hex_num="0x20"
new_dec=`printf "%02d\n" "$hex_num"`
echo ${new_dec}
輸出結果
20
32