]> rtime.felk.cvut.cz Git - pes-rpp/rpp-test-sw.git/blob - rpp/lib/cmdproc/src/i2str.c
b084c5cd329308a009e220f8755dc9e52f9d4c3d
[pes-rpp/rpp-test-sw.git] / rpp / lib / cmdproc / src / i2str.c
1 /*******************************************************************
2   Components for embedded applications builded for
3   laboratory and medical instruments firmware  
4  
5   cmd_i2str.c - formated text to string conversion
6                 without need to pull in whole stdio support
7  
8   Copyright (C) 2001-2010 by Pavel Pisa pisa@cmp.felk.cvut.cz
9             (C) 2002-2010 by PiKRON Ltd. http://www.pikron.com
10             (C) 2007 by Michal Sojka <sojkam1@fel.cvut.cz>
11
12   This file can be used and copied according to next
13   license alternatives
14    - MPL - Mozilla Public License
15    - GPL - GNU Public License
16    - other license provided by project originators
17  *******************************************************************/
18
19 #include "i2str.h"
20
21 /**
22  * Converts integer to string.
23  * @param s Buffer to store the result.
24  * @param val Value to convert.
25  * @param len Minimal width of the converted strign (padded by ' ').
26  * @param form Base of the number.
27  * @return 0
28  */
29 int i2str(char *s,long val,int len,int form)
30 {
31   int sig;
32   int dig=1;
33   int padd=0;
34   unsigned base=form&0xff;
35   unsigned long u;
36   unsigned long mag;
37   unsigned long num;
38   if(!base) base=10;
39   if((sig=(val<0)&&(base==10))) num=-val;
40   else num=val;
41  
42   mag=1;
43   u=base*mag;
44   while(num>=u){
45     dig++;
46     mag=u;
47     if(mag>(unsigned long)(~(unsigned long)0)/base) break;
48     u*=base;
49   }
50
51   if(len){
52     padd=len-dig;
53     if(sig) padd--;
54   }
55   if(padd<0) padd=0;
56
57
58   if(form&I2STR_PAD_0) {
59     if(sig) *(s++)='-';
60     while(padd){
61       *(s++)='0';
62       padd--;
63     }
64   }else{
65     while(padd){
66       *(s++)=' ';
67       padd--;
68     }
69     if(sig) *(s++)='-';
70   }
71
72   while(dig--){
73     u=num/mag;
74     if(u>9) *(s++)='A'-10+u;
75     else *(s++)='0'+u;
76     num=num%mag;
77     mag/=base;
78   }
79   *s=0;
80   return 0;
81 }
82