Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 4th, 2012  |  syntax: None  |  size: 1.56 KB  |  hits: 21  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include "kstring.h"
  2. #include <stdio.h>
  3.  
  4. static const int MAXDIGITS = 20;
  5. static const char char_table[16]
  6.   = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  7.      'a', 'b', 'c', 'd', 'e', 'f'};
  8.  
  9. int int2str(const int n, const int x, char *str)
  10. {
  11.   char buf[MAXDIGITS+2];
  12.   int i, j;
  13.   int y;
  14.   for(i = 0, y = x > 0? x : -x; (i < MAXDIGITS) && (y != 0); ++i, y = y /n) {
  15.     buf[i] = char_table[y % n];
  16.   }
  17.   if(x < 0) {
  18.     buf[i] = '-';
  19.   } else {
  20.     i--;
  21.   }
  22.   for(j = 0; i >= 0; --i, ++j) {
  23.     str[j] = buf[i];
  24.   }
  25.   str[j] = '\0';
  26.   return j;
  27. }
  28.  
  29. int uint2str(const unsigned int n, const unsigned int x, char *str)
  30. {
  31.   char buf[MAXDIGITS+2];
  32.   int i, j;
  33.   unsigned int y;
  34.   for(i = 0, y = x; (i < MAXDIGITS) && (y != 0); ++i, y = y /n) {
  35.     buf[i] = char_table[y % n];
  36.   }
  37.   i--;
  38.   for(j = 0; i >= 0; --i, ++j) {
  39.     str[j] = buf[i];
  40.   }
  41.   str[j] = '\0';
  42.   return j;
  43. }
  44.  
  45.  
  46. int sprint_int(char *str, const char *format, ...)
  47. {
  48.   int *varg = (int*)(&format + 1);
  49.   int fi, vi;
  50.   char *s;
  51.   for(fi = 0, vi = 0, s = str; format[fi] != '\0'; ++fi) {
  52.     if(format[fi] == '%') {
  53.       if(format[fi+1] == 'd') {
  54.         int n = int2str(10, varg[vi], s);
  55.         s = s + n;
  56.         fi++;
  57.         vi++;
  58.         continue;
  59.       } else if(format[fi+1] == 'u') {
  60.         int n = uint2str(10, varg[vi], s);
  61.         s = s + n;
  62.         fi++;
  63.         vi++;
  64.         continue;
  65.       } else if(format[fi+1] == 'x') {
  66.         int n = uint2str(16, varg[vi], s);
  67.         s = s + n;
  68.         fi++;
  69.         vi++;
  70.         continue;
  71.       }
  72.     }
  73.     *s = format[fi];
  74.     s++;
  75.   }
  76.   *s = '\0';
  77.   return 0;
  78. }