-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbasecvt
More file actions
executable file
·35 lines (26 loc) · 967 Bytes
/
Copy pathbasecvt
File metadata and controls
executable file
·35 lines (26 loc) · 967 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/bin/bash
# base conversion between: binary, octal, decimal, and hexadecimal
# usage: basecvt input_base output_base input_number
# created by zhouwei on 2020-10-01
set -e
if [[ $# != 3 ]]; then
echo "Usage: basecvt input_base output_base input_number"
echo "For example: basecvt 2 10 1111 # it will return 15"
exit 1
fi
input_base=$1
output_base=$2
input_number=$3
input_number=$(echo "$input_number" | awk '{print(toupper($1))}')
if [[ $input_base -eq 2 ]]; then
input_number=$(echo "$input_number" | sed -E 's/^0B//g')
elif [[ $input_base -eq 16 ]]; then
input_number=$(echo "$input_number" | sed -E 's/^0X//g')
fi
# check the parameters, for example: 19 is a illegal input_number for input_base=8
echo "$((${input_base}#${input_number}))" >/dev/null
if [[ "$?" != 0 ]]; then
echo "ERROR: input_number ${input_number} is illegal for input_base ${input_base}"
exit 1
fi
echo "obase=${output_base}; ibase=${input_base}; $input_number" | bc