Return an 8-bit array in Python

0

I'm doing a program for a Vúmetro in python where I need to return an array of values in 8-bit binary, but when I run my program it returns the array but in a way that the 8 0's are executed first and then a 1 with 7 0's , two 1's with 6 0's, ... but I need the first to execute the 8 0's then in the first position, execute 1 and 7 0's and in the third execution the 1 will be shown in the second position and so on until the 8 positions.

This is my Python code:

import time

Array = [18, 23, 24, 25, 12, 16, 20, 21]

def  binario(numero):
    ceros=8-numero

    resultado = []

    for i in range(8): 
       resultado.append(numero & 1)
       numero >>= 1
    return resultado


contador = 0

while True:
     contador = (contador + 1)%256
     print(contador)

     for bit in zip(Array,binario(contador)):
         print(bit)
    
asked by Saul115 23.09.2018 в 19:20
source

1 answer

0

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]
    
answered by 23.09.2018 в 20:54