1 /*
2  * (c) Copyright 1990 Conor P. Cahill (uunet!virtech!cpcahil).
3  * You may copy, distribute, and use this software as long as this
4  * copyright statement is not removed.
5  */
6 #include "tostring.h"
7 
8 /*
9  * Function:	tostring()
10  *
11  * Purpose:	to convert an integer to an ascii display string
12  *
13  * Arguments:	buf	- place to put the
14  *		val	- integer to convert
15  *		len	- length of output field (0 if just enough to hold data)
16  *		base	- base for number conversion (only works for base <= 16)
17  *		fill	- fill char when len > # digits
18  *
19  * Returns:	length of string
20  *
21  * Narrative:	IF fill character is non-blank
22  *		    Determine base
23  *		        If base is HEX
24  *		            add "0x" to begining of string
25  *		        IF base is OCTAL
26  *		            add "0" to begining of string
27  *
28  *		While value is greater than zero
29  *		    use val % base as index into xlation str to get cur char
30  *		    divide val by base
31  *
32  *		Determine fill-in length
33  *
34  *		Fill in fill chars
35  *
36  *		Copy in number
37  *
38  *
39  * Mod History:
40  *   90/01/24	cpcahil		Initial revision.
41  */
42 
43 #ifndef lint
44 static
45 char rcs_hdr[] = "$Id: tostring.c,v 1.2 2006-07-25 10:10:17 rt Exp $";
46 #endif
47 
48 #define T_LEN 10
49 
50 int
tostring(buf,val,len,base,fill)51 tostring(buf,val,len,base,fill)
52 	int	  base;
53 	char	* buf;
54 	char	  fill;
55 	int	  len;
56 	int	  val;
57 
58 {
59 	char	* bufstart = buf;
60 	int	  i = T_LEN;
61 	char	* xbuf = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
62 	char	  tbuf[T_LEN];
63 
64 	/*
65 	 * if we are filling with non-blanks, make sure the
66 	 * proper start string is added
67 	 */
68 	if( fill != ' ' )
69 	{
70 		switch(base)
71 		{
72 			case B_HEX:
73 				*(buf++) = '0';
74 				*(buf++) = 'x';
75 				if( len )
76 				{
77 					len -= 2;
78 				}
79 				break;
80 			case B_OCTAL:
81 				*(buf++) = fill;
82 				if( len )
83 				{
84 					len--;
85 				}
86 				break;
87 			default:
88 				break;
89 		}
90 	}
91 
92 	while( val > 0 )
93 	{
94 		tbuf[--i] = xbuf[val % base];
95 		val = val / base;
96 	}
97 
98 	if( len )
99 	{
100 		len -= (T_LEN - i);
101 
102 		if( len > 0 )
103 		{
104 			while(len-- > 0)
105 			{
106 				*(buf++) = fill;
107 			}
108 		}
109 		else
110 		{
111 			/*
112 			 * string is too long so we must truncate
113 			 * off some characters.  We do this the easiest
114 			 * way by just incrementing i.  This means the
115 			 * most significant digits are lost.
116 			 */
117 			while( len++ < 0 )
118 			{
119 				i++;
120 			}
121 		}
122 	}
123 
124 	while( i < T_LEN )
125 	{
126 		*(buf++) = tbuf[i++];
127 	}
128 
129 	return( (int) (buf - bufstart) );
130 
131 } /* tostring(... */
132 
133