asm/decimal.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Tue, 13 Oct 2009 19:03:36 +0200
changeset 108 d6a52e0152fb
parent 77 49e0babccb23
child 142 d6bce20b455e
permissions -rw-r--r--
Compont Literals in C aka Anonymous arrays committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * asm/decimal.c
 * Copyright (C) 2008 Markus Broeker
 */

#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;
}