asm/decimal.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Fri, 19 Nov 2010 16:32:43 +0100
changeset 160 26414889dded
parent 142 d6bce20b455e
permissions -rw-r--r--
removed unneeded includes and code cleanups 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>

#ifndef __WORDSIZE
#define __WORDSIZE 32
#endif

#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 != NULL)
            free (binaer);
    }
    return EXIT_SUCCESS;
}