[ create a new paste ] login | about

Link: http://codepad.org/6QSt0oRy    [ raw code | output | fork ]

C, pasted on Oct 5:
#include <stdio.h>
int   convi(const char* s);
char* iconv(char* s, int n, int r);


int  main(void) {
   char buf[33];

   int n = convi(" 2012 year");

   printf("dec: %d\n", n);
   printf("bin: %s\n", iconv(buf, n, 2));
   printf("oct: %s\n", iconv(buf, n, 8));
   printf("hex: %s\n", iconv(buf, n, 16));
   return 0;
}



// строка в число
int convi(const char* s) {
   int n = 0, i = 1;

   if(! *s)
         return 0;

   while(*s && !(*s >= '0' && *s <= '9'))
       ++s;

   if(*(s - 1) == '-')
       i = -i;

   while(*s && (*s >= '0' && *s <= '9')) {
       n *= 10;
       n += (int)(*s++ - '0');
   }
   return n * i;
}




// 10-число в 2, 8, 16
char* iconv(char* s, int n, int r) {
   char c, *p, *t = s;
   size_t i;

   const char ts[] = {
      '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
      'A', 'B', 'C', 'D', 'E', 'F'
   };

   for(i = (size_t)n; i != 0; i /= r)
       *s++ = ts[i % r];
	
   if(s == t)
       *s++ = '0';
   *s = '\0';	

   for(--s, p = t; s > p; --s, ++p) {
       c  = *p;
       *p = *s;
       *s = c;
   }
   return t;
}


Output:
1
2
3
4
dec: 2012
bin: 11111011100
oct: 3734
hex: 7DC


Create a new paste based on this one


Comments: