0

I'm learning to code with bash, I want to convert a decimal number to a binary array, the problem is that I can't count the number of elements in the array.

My code is:

read -p 'Ingrese primer numero: ' numero_1

function binario(){
 num=$1
 arr1=()
 i=0
 while [ $num -ne 0 ]
 do
  div=$(($num/2))
  rem=$(($num%2))
  num=$div
  arr1=("$rem" "${arr1[*]}")
  echo ${arr1[*]}
 done
 echo "array 1 es ${arr1[*]}"
 echo "largo dentro de la funcion ${#arr1[*]}"
}
binario $numero_1

the counting does not work. In my console, I obtain this information:

Ingrese primer numero: 56
array 1 es 1 1 1 0 0 0
largo dentro de la funcion 1

I know that I'm doing something wrong, but I don't know what, Can you please help me?

Thanks in advance

1 Answer 1

4

Replace the * with a @ to populate the array with the elements of the array instead of treating the whole array as one element:

- arr1=("$rem" "${arr1[*]}")
+ arr1=("$rem" "${arr1[@]}")

* expands to one word, @ expands to a list of words.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.