A int
will have (almost) always 32 bits, so you know the required size. Even if you don’t know it, in cases like this it’s best to allocate enough for as long as possible. It’s actually something so simple that you shouldn’t allocate dynamically. Do the allocation as vector yourself and don’t worry about it.
As the comments I made a code to at least demonstrate the functioning (as information is missing in the question, it will need adaptations):
#include <stdio.h>
int main(void) {
int inteiro = 3;
int tamanho = sizeof(int) * 8; //aqui acha o tamanho de um int
char binario[tamanho + 1]; //aqui aloca o vetor de char com espaço para o terminador
int i = tamanho - 1; //inicia o contador
while (i > 0) {
binario[i] = inteiro % 2 + 48; //acha o binário
inteiro /= 2;
i--;
}
binario[tamanho] = '\0'; //coloca o terminador
printf("%s", binario);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Note that he does not consider the endianness.
trial
vetor[sizeof(int)*8]
, I think so of.– Skywalker
Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?
– Maniero