Your function returns an array of integers, in which each integer is a bit of the binary representation of the number. It returns "upside down" in the sense that the first bit of the array is the lowest bit of the result.
So, for example, if you pass as a parameter the number 18, which in binary would be 00010010, your function returns the list [0, ,1, 0, 0, 1, 0, 0, 0]
that you can check that contains the correct bits but "backwards".
When you invoke that function in a loop, from the main program, passing it an increasing integer ( contador
) what you get is the binary representation of all the numbers from 0 to 255.
From your description of the question it seems that what you wanted rather is a list in which all the bits are at 0, except one, which is moving from left to right. That obviously is not the binary representation of the number.
In this case I can understand that the numero
parameter that the function receives could be used to indicate in which position of the 8 bits we want 1. If the parameter is 0, all the bits will be 0. If it is 1, the first bit will be 1, if it is 2, the second bit will be 1, etc.
In this case I do not see any sense in passing a number greater than 8 to the function.
This would be an implementation of the function you are looking for, if I understand you correctly:
def binario(numero):
resultado = [0] * 8 # Preparamos una lista de 8 ceros
numero %= 9 # Asegurarse de que numero está entre 0 y 8
if numero > 0:
# Cambiamos a 1 un bit de la lista
resultado[numero -1] = 1
return resultado
for i in range(9):
print(i, binario(i))
Execution produces:
0 [0, 0, 0, 0, 0, 0, 0, 0]
1 [1, 0, 0, 0, 0, 0, 0, 0]
2 [0, 1, 0, 0, 0, 0, 0, 0]
3 [0, 0, 1, 0, 0, 0, 0, 0]
4 [0, 0, 0, 1, 0, 0, 0, 0]
5 [0, 0, 0, 0, 1, 0, 0, 0]
6 [0, 0, 0, 0, 0, 1, 0, 0]
7 [0, 0, 0, 0, 0, 0, 1, 0]
8 [0, 0, 0, 0, 0, 0, 0, 1]