Matrix Binaria in C

Asked

Viewed 288 times

0

I need to initialize a matrix that contains the binary values from 0 to the input value, which in this case is 15. The base conversion and the storage of these values works well until the number 8. However, from the 9 line, where the last digit should be 1, only zero is printed and this remains until the end of execution. Here’s the code I’m using:

    int conversor(entrada)
{
    aux1=entrada;
    do
    {
        /*
        Na função usei o modelo da divisão continua para converter um número, que se dá da seguinte maneira:
        Usando um inteiro na base decimal, é divido constantemente até que o divisor de zero
        O resto de cada uma dessas divisões é apenas 0 ou 1, e ordendando da direita para a esquerda,
         o resultado é em binario
        */
        for (i=entrada; i>=0; i--)
        {
            do
            {
                if (aux==0)
                {
                    saida[i][aux]=entrada%2;
                    divisor=entrada/2; //Primeira iteração, usa o valor de entrada ainda
                }
                else
                {
                    saida[i][aux]=divisor%2;
                    divisor=divisor/2; //Termina de dividir o numero
                }
                aux++; //Proxima coluna
            }
            while (divisor>0); //Faz a conta enquanto o divisor for maior que zero
        }
        entrada--; //Passa para proxima linha
        aux=0; //Zera auxiliar
    }
    while (entrada>0);

    for (j=0; j<=aux1; j++)
    {
        for (i=3; i>=0; i--)
        {
            printf ("%d ",saida[j][i]);
        }
        printf("\n");
    }
}

And here is the result:

0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 0
1 0 1 0
1 0 1 0
1 1 0 0
1 1 0 0
1 1 1 0
1 1 1 0

I have tried to test array initialization only to contain the binary value of 9, 1001, separately but when I run this function this error happens. What I’m doing wrong?

  • What is entrada? typedef, #define, you forgot to write the variable type? And why is there no variable declaration? They are all global?

1 answer

0


It is pertinent to avoid these transformations by making module/division and resorting to displacement operators. Easily, you can extract the bits to solve your problem. Considering an integer whose binary value fits in a 4 digit representation:

#include <stdio.h>

const int MAX_VALUE = 15;

int main (void) {

  int MBIN[15][4] = {{0}};

  for (int i = 0; i < MAX_VALUE; i++) {
     MBIN[i][0] = (i >> 3) & 0x1;
     MBIN[i][1] = (i >> 2) & 0x1;
     MBIN[i][2] = (i >> 1) & 0x1;
     MBIN[i][3] = i & 0x1
   }

   // Mostrando os valores da matriz
   for (int i = 0; i < MAX_VALUE; i++) {
    for (int j = 0; j < 4; j++) {
        printf("%d", MBIN[i][j]);
     }
    puts("");
   }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.