LoginSignup
1
1

More than 3 years have passed since last update.

Bashだけで16進数・10進数・2進数間の相互変換を行う

Last updated at Posted at 2020-10-06

2進数から10進数に変換する。

bin2dec.sh
# convert binary number to decimal number
# bin2dec 101 # -> 5
function bin2dec()
{
  echo $((2#$1))
}

2進数から16進数に変換する。

bin2hex.sh
# convert binary number to hexadecimal  number
# bin2hex 1011 # -> B
function bin2hex()
{
  printf '%X' $((2#$1))
}

10進数から2進数に変換する。

dec2bin.sh
# convert decimal number to binary number
# dec2bin 5 # -> 101
function dec2bin()
{
  local b c o2b
  o2b='000001010011100101110111'
  b=$( printf '%o' $1 | while read -N 1 c; do echo -n ${o2b:$((c*3)):3}; done )
  b=${b#0}
  b=${b#0}
  echo $b
}

10進数から16進数に変換する。

dec2hex.sh
# convert decimal number to hexadecimal  number
# dec2hex 11 # -> B
function dec2hex()
{
  printf '%X' $1
}

16進数から2進数に変換する。

hex2bin.sh
# convert hexadecimal number to binary number
# hex2bin B # -> 11
function hex2bin()
{
  local b c h2b
  h2b='0000000100100011010001010110011110001001101010111100110111101111'
  b=$( echo -n $1 | while read -N 1 c; do c=$((16#$c)); echo -n ${h2b:$((c*4)):4}; done )
  b=${b#0}
  b=${b#0}
  b=${b#0}
  echo $b
}

16進数から10進数に変換する。

hex2dec.sh
# convert hexadecimal number to decimal number
# bin2dec 101 # -> 5
function hex2dec()
{
  echo $((16#$1))
}

補足

自由に使っていただいて構いませんが、エラー処理や引数チェックは適時追加してください。動作保証や損害賠償は一切致しません、各自の責任でご利用ください。
参考記事→Bashだけで10進数からn進数(2~64進数)に変換する

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1