Created
July 23, 2019 21:04
-
-
Save ctnguyenvn/bf533da434d2ab484bf3196b5b8f0d98 to your computer and use it in GitHub Desktop.
dec to binary
This file contains 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<string.h> | |
#include<stdlib.h> | |
// function reverse string instead of strrev (strrev not exist in linux) | |
char *rev_string(char *str) | |
{ | |
int start = 0; | |
int end = strlen(str) - 1; | |
char tmp; | |
if (!str || !*str) | |
{ | |
exit(0); | |
} | |
while(start < end) | |
{ | |
tmp = *(str + start); | |
*(str + start) = *(str + end); | |
*(str + end) = tmp; | |
start++; | |
end--; | |
} | |
return str; | |
} | |
// function covert decimal to binary (to string -> reverse string) | |
char *dec2bin(int n) | |
{ | |
char *str = (char *)malloc(100 * sizeof(char)); | |
int i = 0; | |
while(n > 0) | |
{ | |
if(n % 2 == 0) | |
{ | |
*(str + i) = '0'; | |
} | |
else | |
{ | |
*(str + i) = '1'; | |
} | |
i++; | |
n = n / 2; | |
} | |
return rev_string(str); | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
int number; | |
char *binary = (char *)malloc(100 * sizeof(char)); | |
printf("Number: "); | |
scanf("%d", &number); | |
binary = dec2bin(number); | |
printf("Ket qua: "); | |
puts(binary); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment