--- /dev/null
+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
--- /dev/null
+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.
--- /dev/null
+#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");
+
+}
+