conv.c -- simple numeric base converter

Jef Poskanzer jef at well.sf.ca.us
Wed Jul 4 01:05:12 AEST 1990


For such a simple interface, a script front-ending for bc would
work too.  For a somewhat more interesting interface, see below.
It's a base-conversion filter -- looks for any numbers in stdin,
converts them from any base to any base in [2..36], and leaves
non-numeric text alone.
---
Jef

  Jef Poskanzer  jef at well.sf.ca.us  {ucbvax, apple, hplabs}!well!jef
       "Publish and be damned." -- Wellesley, Duke of Wellington

/*
** baseconvert.c - base conversion filter
**
** Copyright (C) 1989 by Jef Poskanzer.
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation.  This software is provided "as is" without express or
** implied warranty.
*/

#include <stdio.h>
#include <strings.h>
#include <ctype.h>

static char *idigits = "0123456789abcdefghijklmnopqrstuvwxyz";
static char *odigits = "0123456789abcdefghijklmnopqrstuvwxyz";

main( argc, argv )
int argc;
char *argv[];
    {
    int ibase, obase;
    char *usage = "usage: %s <ibase> <obase>\n";
    int ic, i, gettingi, digit;
    char c, lc;
    char *digitp;
    void putint( );

    if ( argc != 3 ||
	 ( ibase = atoi( argv[1] ) ) < 2 || ibase > 36 ||
	 ( obase = atoi( argv[2] ) ) < 2 || obase > 36 )
	{
	fprintf( stderr, usage, argv[0] );
	exit( 1 );
	}
    idigits[ibase] = '\0';

    gettingi = 0;
    for ( ; ; )
	{
	ic = getchar( );
	if ( ic == EOF ) break;
	c = ic;
	if ( isupper( c ) )
	    lc = tolower( c );
	else
	    lc = c;
	digitp = index( idigits, lc );
	if ( digitp == (char *) 0 )
	    {
	    if ( gettingi )
		{
		putint( i, obase );
		gettingi = 0;
		}
	    putchar( c );
	    }
	else
	    {
	    digit = digitp - idigits;
	    if ( gettingi )
		{
		i = i * ibase + digit;
		}
	    else
		{
		gettingi = 1;
		i = digit;
		}
	    }
	}
    
    if ( gettingi )
	putint( i, obase );

    exit( 0 );
    }

void
putint( i, base )
int i, base;
    {
    if ( i >= base )
	putint( i / base, base );
    putchar( odigits[i % base] );
    }



More information about the Alt.sources mailing list