1
The code below, from the original (http://www.programasprontos.com/algoritmos-conversores/conversao-decimal-para-binario-c/) "prints" a decimal number between 0 and 255 in binary.
#include <stdio.h>
#include <stdlib.h>
int main() {
int n; // Número de entrada
int r; // Resultado do deslocamento
int i; // Contador
printf("Digite o numero: ");
scanf("%d", &n);
// Utiliza um número de 32 bits como base para a conversão.
for(i = 7; i >= 0; i--) {
// Executa a operação shift right até a última posição da direita para cada bit.
r = n >> i;
if(r & 1) {
printf("1");
} else {
printf("0");
}
}
printf("\n");
}
I need to convert multiple numbers to decimal (between 0 and 255) p/ binary and then vice versa. So I see that it would be useful to use the above code logic in a função
p/ make the conversion, or even a for
huge (despite finding the second option unfeasible).
The vectors:
char *num_corresp_int;
num_corresp_int = (char *) malloc(tamanho * sizeof(char));
char *vetor_binario;
vetor_binario = (char *) malloc(tamanho * sizeof(char)); // cada posicao do vetor_binario
// so precisara ter 8 bits e nada mais.
are dynamically allocated. Being that the vector num_corresp_int
stores decimal numbers and vector vetor_binario
sequentially store the binary numbers (of the corresponding decimal places).
Example: if num_corresp_int[0] = 65
and num_corresp_int[1] = 66
, the vetor_binario
of position [0]
to [7]
shall have the following corresponding numbers from 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 the binary representation of a decimal number of ASCII table between 0 and 255.
How do I have to transform and store undefined decimal numbers into binary, and then the other way around, what’s the best solution? Create a função
or a for
huge?
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site,
– Maniero