這輸出101110
echo "obase=2; 46" | bc
我怎樣才能讓它輸出8位數字,像這樣?:00101110
我在這里學到了上面的用法bc:Bash shell Decimal to Binary base 2 conversion
另請參閱我對這個問題的回答。
uj5u.com熱心網友回復:
簡單的解決方案是使用bc命令替換中的輸出,為printf使用"d"轉換說明符提供輸入,例如
$ printf "d\n" $(echo "obase=2; 46" | bc)
00101110
uj5u.com熱心網友回復:
其他一些解決方案:
echo "obase=2; 46" | bc | awk '{ printf("d\n", $0) }'
echo "obase=2; 46" | bc | numfmt --format=f
uj5u.com熱心網友回復:
如果有更簡單的方法我想知道,但這是我剛剛撰寫的一個手動執行的函式:
decimal_to_binary_string.sh :(來自我的eRCaGuy_hello_world 存盤庫)
# Convert a decimal number to a binary number with a minimum specified number of
# binary digits
# Usage:
# decimal_to_binary <number_in> [min_num_binary_digits]
decimal_to_binary() {
num_in="$1"
min_digits="$2"
if [ -z "$min_chars" ]; then
min_digits=8 # set a default
fi
binary_str="$(echo "obase=2; 46" | bc)"
num_chars="${#binary_str}"
# echo "num_chars = $num_chars" # debugging
num_zeros_to_add_as_prefix=$((min_digits - num_chars))
# echo "num_zeros_to_add_as_prefix = $num_zeros_to_add_as_prefix" # debugging
zeros=""
for (( i=0; i<"$num_zeros_to_add_as_prefix"; i )); do
zeros="${zeros}0" # append another zero
done
binary_str="${zeros}${binary_str}"
echo "$binary_str"
}
# Example usage
num=46
num_in_binary="$(decimal_to_binary "$num" 8)"
echo "$num_in_binary"
輸出:
00101110
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/447746.html
下一篇:宣告BASH。腳本中的字串陣列
