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.
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.
The simple solution is to use the output of bc
within a command substitution providing input to printf
using the "%08d"
conversion specifier, e.g.
$ printf "%08d\n" $(echo "obase=2; 46" | bc)
00101110
printf
a long time ago in C, so it's kinda the go-to for formatting wanted integer (or binary) output in this case. Since we are talking less than 8 digits, you can treat the binary output with a leading 1
as an integer :)
–
Twopiece printf
version which I had come up with here: printf "0b%s\n" "$(echo "obase=2; $((num1 + num2))" | bc)"
. I was thinking of the output of bc
as a string, not a decimal integer. –
Conscript "0b"
prefix if you like. Good luck with your scripting! –
Twopiece 0
, e.g. str=" 101110"; str="${str// /0}"
–
Twopiece Some other solutions:
echo "obase=2; 46" | bc | awk '{ printf("%08d\n", $0) }'
echo "obase=2; 46" | bc | numfmt --format=%08f
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
© 2022 - 2024 — McMap. All rights reserved.
101110
is not a decimal (%d
) integer number (and in C, which my mind focuses on more, this would be a string, which really isn't a decimal number!). Yet...technically, in bash at least, the string101110
can be / is a decimal number, andprintf
in bash is ok treating it like one, so this works. – Conscript