asm/decimal.c
changeset 5 d752cbe8208e
child 9 c3fecc82ade6
new file mode 100644
--- /dev/null
+++ b/asm/decimal.c
@@ -0,0 +1,110 @@
+/**
+ * $Id: decimal.c,v 1.1.1.1 2008-04-28 17:32:52 mbroeker Exp $
+ * $Source: /development/c/asm/decimal.c,v $
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+
+#define  MAXBITS __WORDSIZE
+#define  MAXVALUE ULONG_MAX
+
+typedef unsigned long int ULONG;
+
+void usage (char *name)
+{
+    printf ("Usage: %s start [end] [base]\n", name);
+}
+
+/*
+ * Computes the binary representation of a
+ * decimal value and returns the result
+ * in proper order and the number of digits
+ */
+
+char *dec_to_base (ULONG decimal, int base, int *digits)
+{
+    char *encoded;
+    char swp;
+    int i;
+
+    i = 0;
+
+    if ((decimal > MAXVALUE)) {
+        perror ("VALUE TOO BIG");
+        return NULL;
+    }
+
+    if ((encoded = malloc ((MAXBITS) * sizeof (char))) == NULL) {
+        perror ("MALLOC ERROR");
+        return NULL;
+    }
+
+    while (decimal > base - 1) {
+        encoded[i++] = (decimal % base);
+        decimal /= base;
+    }
+    encoded[i++] = (decimal % base);
+    *digits = i;
+
+    for (i = 0; i < *digits - 1; i++) {
+        swp = encoded[*digits - i - 1];
+        encoded[*digits - i - 1] = encoded[i];
+        encoded[i] = swp;
+    }
+
+    return encoded;
+}
+
+int main (int argc, char **argv)
+{
+    ULONG decimal, start, end;
+    int bits, base, i;
+    char *binaer;
+
+    base = 2;
+
+    if (argc == 2) {
+        start = atol (argv[1]);
+        end = start + 1;
+    } else if (argc == 3) {
+        start = atol (argv[1]);
+        end = atol (argv[2]);
+    } else if (argc == 4) {
+        start = atol (argv[1]);
+        end = atol (argv[2]);
+        base = atoi (argv[3]);
+    } else {
+        usage (argv[0]);
+        return EXIT_SUCCESS;
+    }
+
+    if (!((start >= 0) && (end > start) && (base > 1))) {
+        usage ("Trottel");
+        printf ("%ld\t%ld\t%d\n", start, end, base);
+        return EXIT_SUCCESS;
+    }
+
+    printf ("\tVALUE \t\tDIGITS\t\t Encoded\n");
+    printf ("----------------------------------------------------\n");
+
+    for (decimal = start; decimal < end; decimal++) {
+        if ((binaer = dec_to_base (decimal, base, &bits)) == NULL) {
+            return EXIT_FAILURE;
+        }
+
+        printf ("%12ld %12d \t\t", decimal, bits);
+
+        for (i = 0; i < bits; i++) {
+            printf ("%X", binaer[i]);
+        }
+        printf ("\n");
+
+        if (binaer)
+            free (binaer);
+    }
+    return EXIT_SUCCESS;
+}