Skip to content

Instantly share code, notes, and snippets.

@gvillalta99
Created August 14, 2014 19:13
Show Gist options
  • Save gvillalta99/d1b6315761c75dba9c4a to your computer and use it in GitHub Desktop.
Save gvillalta99/d1b6315761c75dba9c4a to your computer and use it in GitHub Desktop.
#include <stdio.h>
#define TAMANHO 128
long converteBinario(char[]);
int tamanho(char[]);
int potencia2(int);
int main(int argc, char *argv[]){
char input1[TAMANHO];
char input2[TAMANHO];
long numero1 = 0l;
long numero2 = 0l;
puts("Entre com o valor binario do primeiro numero:");
scanf("%s", &input1);
puts("Entre com o valor binario do segundo numero:");
scanf("%s", &input2);
numero1 = converteBinario(input1);
numero2 = converteBinario(input2);
printf("Primeiro numero: %ld\n", numero1);
printf("Segundo numero: %ld\n", numero2);
return 0;
}
#define ZERO '0'
#define UM '1'
#define QUEBRA '\0'
long converteBinario(char input[]){
long numero = 0l;
int i = 0;
int bit = 0;
int size = tamanho(input);
for(i=0; i<TAMANHO; i++){
if (input[size -i -1] == QUEBRA)
break;
if (input[size - i -1] == ZERO)
bit = 0;
else if (input[size - i -1] == UM)
bit = 1;
else
break;
numero += bit * potencia2(i);
}
return numero;
}
int tamanho(char input[]){
int tamanho = 0;
for(tamanho = 0; tamanho < TAMANHO; tamanho++)
if(input[tamanho] != ZERO && input[tamanho] != UM) break;
return tamanho;
}
int potencia2(int i) {
return i == 0 ? 1 : 2*potencia2(i-1);
}
Entre com o valor binario do primeiro numero:
Entre com o valor binario do segundo numero:
output1: 8
output2: 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment