Created
September 10, 2015 13:34
-
-
Save magnunleno/4c9bab0c34cfcd3c5e96 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
char* int_to_bin_str(unsigned int n) { | |
int i; | |
int mask = 1; | |
char *str_n = (char*)malloc(32); | |
for (i = 0; i < 32; i++) { | |
if (mask & n) | |
str_n[31-i] = '1'; | |
else | |
str_n[31-i] = '0'; | |
mask = mask << 1; | |
} | |
return str_n; | |
} | |
unsigned int bin_str_to_int(char *n_str) { | |
int i; | |
unsigned int result = 0; | |
unsigned int power = 1; | |
for (i = 31; i >= 0; i--){ | |
if (n_str[i] == '1') | |
result = result + power; | |
power = power << 1; | |
} | |
return result; | |
} | |
int main(int argc, char** argv) { | |
int i; | |
unsigned int result; | |
bool carry_one = false; | |
char *result_str = (char*)malloc(32); | |
char *n1 = int_to_bin_str(10); | |
char *n2 = int_to_bin_str(11); | |
for (i = 31; i >= 0; i--) { | |
if (n1[i] == '0' && n2[i] == '0') { | |
if (carry_one == true) { | |
result_str[i] = '1'; | |
carry_one = false; | |
} else { | |
result_str[i] = '0'; | |
} | |
} | |
if ((n1[i] == '1' && n2[i] == '0') || (n1[i] == '0' && n2[i] == '1')) { | |
if (carry_one == true) | |
result_str[i] = '0'; | |
else | |
result_str[i] = '1'; | |
} | |
if (n1[i] == '1' && n2[i] == '1') { | |
if (carry_one == true) { | |
result_str[i] = '1'; | |
} else { | |
result_str[i] = '0'; | |
carry_one = true; | |
} | |
} | |
} | |
result = bin_str_to_int(result_str); | |
printf("Resultado = %i (%s)\n", result, result_str); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment