The code below, from the original ( link ) "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 into decimal ( between 0 and 255 ) for binary and then vice versa. So I see that it would be useful to use the above code logic in a função
to make the conversion, or even a huge for
(although it seems impracticable the 2nd option).
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. Since the num_corresp_int
vector stores the numbers in decimal and the vetor_binario
vector will sequentially store the numbers in binary (of the corresponding decimals).
Example: If num_corresp_int[0] = 65
and num_corresp_int[1] = 66
, vetor_binario
from [0]
to [7]
should have the following corresponding numbers in the ASCII table: 01000001
e, from [8]
to [15]
the following numbers: 01000010
. That is, every 8 positions of vetor_binario
will have the binary representation of a decimal number of the ASCII table between 0 and 255 .
How do I have to transform and store indefinite decimal numbers in binary, and then the opposite also, what is the best solution? Create a função
or a for
huge?