Hi, I am trying to do a bash script that convert a decimal number to a binary value, but it doesn't work...
To begin, I am just trying to convert a positive number to 8 bits binary.
read -p"Entrez un nombre entre -128 et 127 pour l'encoder en binaire: " number
binaryValues=(128 64 32 16 8 4 2 1)
binaryNumber=()
positiveNum=$number
if [ $number -lt 0 ] #transformer la copie du nombre en positif.
then
(( positiveNum=$number-$number*2 ))
fi
for i in "${binaryValues[@]}"
do
if (( $positiveNum -ge ${binaryValues} ))
then
positiveNum=$"(( $positiveNum-${binaryValues} ))"
binaryNumber='1';
else
binaryNumber='0';
fi
done
echo ${binaryNumber[@]}
; then i will contain the value, not the array index in every iteration -ge is incorrect syntax within (( ... )) , that should be >= $"((...))" is incorrect usage of quotes, that should be: $((...))
How about using what's already available and set the length like this:-
#!/bin/bash
number_in=123
length=20 # Perhaps this is ridiculous, but it proves the point.
number_out=$(echo "obase=2 ; print $number_in" | bc)
printf "%0${length}d\n" "${number_out}"
A quicky demo for 0 to 127 only using OSX 10.14.6, default 'bash' version 3.2.x...
Called as [./]decimal2binary.sh <integer_from_0_to_127> ...
#!/bin/bash
# decimal2binary.sh <integer_0_to_127>
NUMBER=${1}
STRING=""
for COUNT in 6 5 4 3 2 1 0
do
M=$(( NUMBER / 2 ))
N=$(( NUMBER % 2 ))
NUMBER=${M}
STRING=${STRING}$( printf "%d" "${N}" )
done
echo "0${STRING:6:1}${STRING:5:1}${STRING:4:1}${STRING:3:1}${STRING:2:1}${STRING:1:1}${STRING:0:1}"
For values -1 to -128 take a look at using binary XOR "relative to zero" for example "-1" becomes binary "11111111"
AMIGA:amiga~> XORED=$(( 00000000 ^ 11111111 ))
AMIGA:amiga~> echo "-1 = ${XORED} relative to the positive value 00000000..."
-1 = 11111111 relative to the positive value 00000000...
AMIGA:amiga~> _