Quantcast
Channel: Bashタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 2867

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

$
0
0

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

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

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

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

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

dec2bin.sh
# convert decimal number to binary number# dec2bin 5 # -> 101function 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 # -> Bfunction dec2hex(){printf'%X'$1}

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

hex2bin.sh
# convert hexadecimal number to binary number# hex2bin B # -> 11function hex2bin(){local b c h2b
  h2b='0000000100100011010001010110011110001001101010111100110111101111'b=$(echo-n$1 | while read-N 1 c;do c=$((16#$c)) echo -n ${o2b:$((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 # -> 5function hex2dec(){echo$((16#$1))}

自由に使っていただいて構いませんが、エラー処理や引数チェックは適時追加して使用してください。動作保証や損害賠償は一切致しません、各自の責任でご利用ください。


Viewing all articles
Browse latest Browse all 2867

Trending Articles