Last active
December 24, 2015 20:19
-
-
Save RoxasShadow/6856845 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 <iostream> | |
| #include <cstdlib> | |
| #include <algorithm> | |
| #define LEN 256 | |
| char* dec2bin(int dec); | |
| int main(int argc, char *argv[]) { | |
| if(argc != 2) { | |
| std::cout << "Input is required" << std::endl; | |
| return 1; | |
| } | |
| std::cout << "Result: 0b"; | |
| /* | |
| A smarter way would be fill the array starting by its end, and then using a compact-like method to delete all the | |
| dirty trash in the string, but I've chosen the faster way. | |
| Another good way (shorter but slowest with big numbers because of the overhead) would be using a recursive algorithm. | |
| */ | |
| int i; | |
| char *bin; | |
| for(i = LEN, bin = dec2bin(std::atoi(argv[1])); i >= 0; --i) | |
| if(bin[i] == '0' || bin[i] == '1') | |
| std::cout << bin[i]; | |
| std::free(bin); | |
| std::cout << std::endl; | |
| return 0; | |
| } | |
| char* dec2bin(int dec) { | |
| int i = 0; | |
| char *bin = new char[LEN](); | |
| while(dec > 0) { | |
| bin[i++] = dec % 2 == 0 ? '0' : '1'; | |
| dec /= 2; | |
| } | |
| bin = (char*)std::realloc(bin, i * sizeof(char)); | |
| return bin; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment