Home > front end >  How to make `bc` output a desired number of base-2 binary digits
How to make `bc` output a desired number of base-2 binary digits

Time:03-22

This outputs 101110

echo "obase=2; 46" | bc

How can I make it output 8 digits, like this? : 00101110

I learned the above usage of bc here: Bash shell Decimal to Binary base 2 conversion

See also my answer to that question here.

CodePudding user response:

The simple solution is to use the output of bc within a command substitution providing input to printf using the "d" conversion specifier, e.g.

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

CodePudding user response:

Some other solutions:

echo "obase=2; 46" | bc | awk '{ printf("d\n", $0) }'
echo "obase=2; 46" | bc | numfmt --format=f

CodePudding user response:

If there's an easier way I'd like to know, but here's a function I just wrote that does it manually:

decimal_to_binary_string.sh: (from my eRCaGuy_hello_world repo)

# 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"

Output:

00101110
  • Related