如何使 `bc` 输出所需数量的 base-2 二进制数字

How to make `bc` output a desired number of base-2 binary digits

这输出 101110

echo "obase=2; 46" | bc

如何让它输出8位数字,像这样? : 00101110

我在这里学习了bc的上述用法:Bash shell Decimal to Binary base 2 conversion

另见 my answer to that question here

简单的解决方案是在命令替换中使用 bc 的输出,使用 "%08d" 转换说明符为 printf 提供输入,例如

$ printf "%08d\n" $(echo "obase=2; 46" | bc)
00101110

如果有更简单的方法我想知道,但这是我刚刚编写的手动执行的函数:

decimal_to_binary_string.sh: (from my 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=""
    min_digits=""
    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

其他一些解决方案:

echo "obase=2; 46" | bc | awk '{ printf("%08d\n", [=10=]) }'
echo "obase=2; 46" | bc | numfmt --format=%08f