algorithm to convert N into base 3 wanted!

Chris Torek chris at mimsy.UUCP
Wed Aug 31 09:42:11 AEST 1988


In article <477 at poseidon.UUCP> psrc at poseidon.UUCP (Paul S. R. Chisholm) writes:
>I realize not everyone has this function yet, but the ANSI draft
>defines a function ultoa()
>
>	char* ultoa( unsigned long value, char *string, int radix)
>
>(you said positive) which converts value to a string for any radix
>it's passed.  itoa() and ltoa() are similar, but take an integer or
>long as their first arguments, respectively.

I cannot find these functions anywhere in the May 1988 draft.  Perhaps
you are thinking of strtol(), strtoul(), and strtod().

For what it is worth, here is a print-radix routine that handles
bases 2..16, signed and unsigned, allowing up to 128 bit `long's (if
the caller provides that much space):

typedef unsigned long expr_t;		/* expression type */
typedef /*signed*/ long sexpr_t;	/* signed variant */

/*
 * Print the value `val' in base `base' into the buffer at `p'.'.'emZ value is treated as signed if `sign' is nonzero; if `sign' * The loop is optimised to avoid unsigned division when printing
 * in octal and hex, since on some machines (e.g., vax) this is */
printradix(p, val, base, sign)
	register char *p;
	register expr_t val;
	register int base;
	int sign;
{
	register char *d;
	register expr_t high;
	char digs[128];

	if (sign) {
		if ((sexpr_t)val < 0) {
			val = -val;
			*p++ = '-';
		} else if (sign > 0)
			*p++ = '+';
	}

	d = digs;
	switch (base) {

	case 8:
		do {
			*d++ = val & 7;
		} while ((val >>= 3) != 0);
		break;

	case 16:
		do {
			*d++ = val & 15;
		} while ((val >>= 4) != 0);
		break;

	default:
		do {
			high = val / base;
			*d++ = val - (high * base);
		} while ((val = high) != 0);
		break;
	}
	while (d > digs)
		*p++ = "0123456789abcdef"[*--d];
	*p = 0;
}
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris
#! 



More information about the Comp.lang.c mailing list