Decimal to binary conversion in C language using ASCII table

Asked

Viewed 1,118 times

0

I have to make a program that reads some characters and "transform" each character into its corresponding number in the ASCII table and then turn that number into binary and store it in an array. My code so far is:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int i;
char mensagem[200];
    printf("Digite a mensagem: ");
        setbuf(stdin, NULL); // limpando o buffer antes de digitar a msg
        fgets(mensagem, 200, stdin); // leitura OK

int tamanho = strlen(mensagem); // pega a quant de caracteres (incluindo '\n')
// vetor de inteiros p/ armazenar os valores correspondentes dos caracteres na tabela ASCII
char *num_corresp_int; 
/* aloca um vetor de inteiros p/ os num correspondentes dos caracteres*/
    num_corresp_int =  malloc((tamanho) * sizeof(char)); 
        
    for(i = 0; i < tamanho; i++){
        num_corresp_int[i] = mensagem[i]; // não está passando o '\0'
    }

char *vetor_binario; // aloca um vetor p/ armazenar os valores em binario
/* char pq preciso de apenas 1 byte p/ representar os números 0 e 1*/
    vetor_binario = malloc((tamanho) * sizeof(char)); 
        
int r;
/* (tamanho * 8) pq alocacarei um bit em cada posicao do vetor_binario*/
int a, j, aux = tamanho * 8; 
    for(i = 7, a = 0, j = 0; i >= 0 && j < aux; j++, i--) {
        r = num_corresp_int[a] >> i;
            if(r & 1) {
                vetor_binario[j] = 1;
            } else {
                vetor_binario[j] = 0;
            }
        if(i == 0){
            a++;
            i = 7;
        }else if(a == tamanho){
            break;
        }
    }

    for(i = 0; i < aux; i++){ // Testar se o armazenamento está sendo feito corretamente
        printf("%d", vetor_binario[i]); 
    }
  printf("\n");
  return 0;
}

So my question is on how to define the full stop condition in the loop:

for(i = 7, a = 0, j = 0; i >= 0 && j < aux; j++, i--) {
        r = num_corresp_int[a] >> i;
            if(r & 1) {
                vetor_binario[j] = 1;
            } else {
                vetor_binario[j] = 0;
            }
        if(i == 0){
            a++;
            i = 7;
        }else if(a == tamanho){
            break;
        }
}

Where the total stop of loop (break) will happen when a, which is used to reach the tamanho the message is equal to tamanho. I think this total stop should look like the one I outlined using if and else if.

Example: If typed A and B on the keyboard, the vector num_corresp_int[0] = 65 and num_corresp_int[1] = 66. And so, the vetor_binario of position [0]to [7]shall store the following corresponding numbers of the ASCII table: 01000001 and, of the position [8]to [15] the following numbers: 01000010. That is, every 8 positions of the vetor_binario we will have together (sequentially) to binary representation of a decimal number of ASCII table between 0 and 255.

Program output now if typed AB on the keyboard:

010000011000010000101000

Let’s see: With the above output, in addition to others I tested, I saw that the program stores the 8 bits of the first character (A) correctly, but already p/ the second character (B) and later, the vetor_binario does not store the 1st bit of characters, only from the 2nd bit onwards. OBS: in this given example, the bits after last bit of the character B are corresponding to the \n, being the last two bits (00) remains that I still don’t know how to remove.

Doubts

  • How to define the full stop condition in the loop?
  • How to solve the problem, where from the 2nd character, the 1st bit is not being stored, and the last bits are over?
  • Complex your question, your code is strange too.. I don’t know how familiar you are with the language, but I suggest you try using different algorithms.. Two important points are: 1- Why are you doing everything in main? structure your code in the right way. 2- Why use vector? consider the possibility of using linkedList, struct and over the breakpoint, to define something more readable and easy, perhaps the use of Recursiveness. As you said yourself, you are a beginner... so try to adhere to good practices from the beginning of your journey. I hope to have helped

  • Looks like another question from you. Absolute certainty that it is not duplicate? Or the existence of this new question would not actually be a clarification of the previous?

  • Jefferson, this new question is almost the same as the previous one, but here is added my code and my problem to solve is much bigger. So I decided to open this new question.

  • Your motivation seems just =], but still I prefer to abstain from any decision

  • What is this variable a? Do you have a statement? There’s a lot of redundancy and confusion there. It’s so much simpler to do that. You really need to use one loop, as 2 seems to be simpler. Do you have any reason to use a array to store, or just used it because it was the way I thought of it?

  • @bigown 1º: the variable a is used to get to the size of the message inserted on the keyboard. That is, it will be the total stop condition of the loop. 2nd: The question I ask is just a small part of the statement with several other things to be solved. 3rd: I only thought of using one for, otherwise I think another solution would be to use a função p/ the conversion. 4º: I am using a p/ array to store bits as I will need to use each of these saved bits later p/ pass p/ a file.

  • It’s that the code is extraordinarily confused, it’s hard to help something like that. Because either you totally isolate and show what you need. If isolating is proof that you yourself find the error, if you do not do it I will give a solution that will not serve you because there are other things omitted in the question. 2 for is much simpler. Function has nothing to do with this, although one would be useful to better organize the code.

Show 2 more comments

1 answer

2


The code is confusing, does a lot of unnecessary things. The question is extensive, but little useful information. One of the reasons you have difficulty is the code is too complex. Even the most experienced ones don’t get along with complicated code. I would do so:

#include <stdio.h>
#include <string.h>

int main(){
    char mensagem[200];
    printf("Digite a mensagem: ");
    fgets(mensagem, 200, stdin);
    mensagem[strcspn(mensagem, "\n")] = 0;
    int tamanho = strlen(mensagem);
    char vetor_binario[tamanho * 8 + 1];
    vetor_binario[tamanho * 8 + 1] = '\0';
    for (int i = 0; i < tamanho; i++) {
        for (int j = 7; j >= 0; j--) vetor_binario[i * 8 + (7 - j)] = ((mensagem[i] >> j) & 1) + '0';
    }
    printf("%s", vetor_binario);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • That’s right. Since I’m a beginner in programming, when I structure my codes I do it in parts, so it was extensive. I see that I will have to study much more to improve this, including in code optimization.

Browser other questions tagged

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