From 196a6e5cde84cf11fec4c18ea9a7d06eb6771f45 Mon Sep 17 00:00:00 2001 From: Huck Boles Date: Thu, 15 Dec 2022 14:01:53 -0600 Subject: [PATCH 1/1] creation --- Makefile | 14 +++++++++++++ README.md | 19 ++++++++++++++++++ printbin.c | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ printbin.h | 8 ++++++++ 4 files changed, 100 insertions(+) create mode 100644 Makefile create mode 100644 README.md create mode 100644 printbin.c create mode 100644 printbin.h diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..92c605f --- /dev/null +++ b/Makefile @@ -0,0 +1,14 @@ +SHELL = /bin/bash +PROG = printbin + +debug: + gcc *.c *.h -Wall -lm -g -o printbin + +printbin: + gcc *.c *.h -Wall -lm -o printbin + +install: + gcc *.c *.h -Wall -lm -o /home/huck/.local/bin/printbin + +clean: + rm /home/huck/.local/bin/printbin diff --git a/README.md b/README.md new file mode 100644 index 0000000..70d6485 --- /dev/null +++ b/README.md @@ -0,0 +1,19 @@ +printbin - A quick utility to print a number in it's binary representation. + +Usage: + + Print a 16 bit representation: + + $ printbin -b 16 1234 + |> 00000100 11010010 + + Print an 8 bit representation of a base 16 number + $ printbin -b 8 -a 16 5a + |> 01011010 + + Accept input and output binary number; + $ printbin + > 333 + |> 00000000 00000000 00000000 00000000 00000000 00000000 00000001 01001101 + +printbin always prints a base 10 number up to 64 bits, unless the number of bits is set with -b, or the base is set with -a. diff --git a/printbin.c b/printbin.c new file mode 100644 index 0000000..e0c1261 --- /dev/null +++ b/printbin.c @@ -0,0 +1,59 @@ +#include "printbin.h" + +int main(int argc, char *argv[]){ + char *a = malloc(20*sizeof(char)); + char *b = malloc(20*sizeof(char)); + char *n = malloc(60*sizeof(char)); + char c; + unsigned long num; + int bits,base; + int x = 0; + + while ((c = getopt (argc, argv, "a:b:")) != -1){ + switch (c) { + /* number base */ + case 'a': + strcpy(a,optarg); + x++; + break; + /* number bits */ + case 'b': + strcpy(b,optarg); + x++; + break; + } + } + + if (x != 0 && argc > 1) strcpy(n,argv[optind]); + if (strcmp(n,"") == 0) scanf("%s",n); + + if (strcmp(a,"") != 0) { + base = strtol(a,NULL,10); + } else { + base = 10; + } + + if (strcmp(b,"") != 0) { + bits = strtol(b,NULL,10); + } else { + bits = 64; + } + + num = strtol(n,NULL,base); + + printbin(num,bits); + return 0; +} + +void printbin(unsigned long i, int n){ + unsigned long mask = pow(2,n-1); + + for (int t = n-1; t >= 0; t-- ){ + printf("%i",((i & mask) == 0) ? 0 : 1); + printf("%s",(t % 8 == 0) ? " " : ""); + mask = mask >> 1; + } + printf("\n"); + +} + diff --git a/printbin.h b/printbin.h new file mode 100644 index 0000000..5cf0452 --- /dev/null +++ b/printbin.h @@ -0,0 +1,8 @@ +#include +#include +#include +#include +#include + +void printbin(unsigned long, int); +unsigned long getnum (int argc, char **argv); -- 2.44.2