Read a vector to a stop bit

Asked

Viewed 64 times

1

I want to read an 8-bit binary vector backwards and stop until I read the last 1.

For example: [00010101] <--- Read until you find the last 1

Vector read: [1010]

Then associate a function for each 1 read and other function for each 0. How do I do it? What would the parameters look like inside a for?

  • @rod_learninh, welcome to Sopt, it would be interesting for you to post the code of your attempt for the staff to help you :D

  • That’s the same as reading front to back from the first 1 ... and then "reverse" the value.

  • Repeated question (in English): http://stackoverflow.com/questions/32668476/reading-a-binary-vector-backwards-with-a-stop-bit

1 answer

1

Hello, Good morning!

I was having trouble understanding your question, but from what I understand, you want to read the '1' and '0' backwards until you stop at last 1 and put them in a new vector. (v1).

I performed a program to exemplify my solution using a character array, since it is binary we will only have two characters (1 and 0). I used the malloc function of the stdlib library to size the vector to 8 bits. (n = 8). n1, i and j are auxiliary variables to perform inverse vector reading.

Follows the code

#include <stdio.h>
#include <stdlib.h>
/*Desenvolva as funções como desejar*/
void funcaoAssociada1 () {
}

void funcaoAssociada0 () {
}
int main () {
   char *v, *v1;
   int i, n, j, n1;
   n = 8;
   j = 0;
   n1 = 0;
   v = malloc (n * sizeof (char));
   v1 = malloc (n* sizeof (char));
   printf ("Digite o vetor binário (sem espaços)\n");
   for (i = 0; i < n; i++)
      scanf ("%c", &v[i]);
   for (i = n-1; i >= 0; i--,j++)
      if (v[i] == '1') n1 = j;
   for (i = 0; i <= n1; i++)
      v1[i] = v[n-1-i];

   v1[i-1] = '\0';/*Caractere nulo, indica fim do vetor*/
   printf ("%s",v1);

   for (i = 0; v1[i] != '\0'; i++)
      if (v1[i] == '1') funcaoAssociada1 ();
      else funcaoAssociada0 ();
   free (v1);   
   return 0;
}

I hope you’ve been helpful. Any doubt comment.

MS

Browser other questions tagged

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