#include	<stdio.h>
#include	"defs.h"

char *
alloc_check(p, e)
char *p, *e;
{
    if (p == NULL) {
	fprintf(stderr, "can't malloc space for %s", e);
	exit(1);
    }
    return p;
}

makeuint(s, n)		/* return n byte quantity from string */
register byte *s;
register int n;
{
    register int x;	/* number being constructed */

    x = 0;
    while (n--)  {
	x <<= 8;
	x |= *s++;
    }
    return x;
}

makeint(s, n)		/* return n byte quantity from string */
register byte *s;
register int n;
{
    int n1;		/* number of bytes	    */
    register int x;	/* number being constructed */

    x = *s++;		/* get first (high-order) byte */
    n1 = n--;
    while (n--)  {
	x <<= 8;
	x |= *s++;
    }

    /* NOTE: This code assumes that the right-shift is an arithmetic, rather
    than logical, shift which will propagate the sign bit right.   According
    to Kernighan and Ritchie, this is compiler dependent! */

    x<<=32-8*n1;
    x>>=32-8*n1;  /* sign extend */

    return x;
}

static int i2b();

inttob(b, x, issigned)
byte *b;
int x;
BOOLEAN issigned;
{
    static unsigned char buf[sizeof(int)+1];
    int i, j, n;

    n = i2b((unsigned int)x, buf);
    if (x == 0)
	i = 0;
    else if (issigned && x > 0) {
	issigned = FALSE;
	i = 0;
    } else
	i = 1;
    if (issigned)
	for (; i+1 < n && buf[i] == 0xff && (buf[i+1]&0x80); i++)
	    ;
    else
	for (; i+1 < n && buf[i] == 0 && (buf[i+1]&0x80) == 0; i++)
	    ;
    for (j = i; j < n; j++)
	b[j-i] = buf[j];
    return n-i;
}

static
i2b(x, b)
unsigned int x;
unsigned char *b;
{
    int n;

    if (x == 0) {
	*b = 0;
	return (1);
    }
    n = i2b(x>>8, b);
    *(b+n) = x & 0xff;
    return (n+1);
}
