From 69c1e5264137c5ff3369acf3c0ece8fbbce67dec Mon Sep 17 00:00:00 2001 From: lshprung Date: Tue, 24 May 2022 12:58:08 -0700 Subject: First commit --- int2bin.c | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 int2bin.c (limited to 'int2bin.c') diff --git a/int2bin.c b/int2bin.c new file mode 100644 index 0000000..4917a3d --- /dev/null +++ b/int2bin.c @@ -0,0 +1,67 @@ +#include +#include +#include +#include + +//globals +int bits = 32; +bool raw = false; + +void print_help(char *name){ + printf("Usage: %s [OPTION]... NUMBER...\n", name); + printf("Convert NUMBER(S) to binary\n\n"); + + printf("Options:\n"); + printf(" -b, --bits\tSpecify number of bits to print (default is 32)\n"); + printf(" -h, --help\tPrint this help message and exit\n"); + printf(" --raw \tPrint only the binary form\n"); +} + +char *to_bin(int n, int bits){ + char *out = malloc(sizeof(char) * (bits+1)); + int i; + + out[bits] = '\0'; + + for(i = bits-1; i >= 0; --i){ + out[i] = (n & 1 ? '1' : '0'); + n /= 2; + } + + return out; +} + + + +int main(int argc, char **argv){ + int i; + + //print help if no arguments + if(argc < 2){ + print_help(argv[0]); + return 0; + } + + //check for arguments + for(i = 1; i < argc; ++i){ + if(!(strcmp(argv[i], "--"))){ + ++i; + break; + } + else if(!(strcmp(argv[i], "-b")) || !(strcmp(argv[i], "--bits"))){ + if(i+1 >= argc) break; //check that the flag was given an argument + bits = atoi(argv[i+1]); + ++i; + } + else if(!(strcmp(argv[i], "-h")) || !(strcmp(argv[i], "--help"))) print_help(argv[0]); + else if(!(strcmp(argv[i], "--raw"))) raw = true; + else break; + } + + //convert each argument to binary + while(i < argc){ + if(!raw) printf("%d -> ", atoi(argv[i])); + printf("%s\n", to_bin(atoi(argv[i]), bits)); + ++i; + } +} -- cgit