Created
January 30, 2012 17:40
-
-
Save mmitou/1705597 to your computer and use it in GitHub Desktop.
簡易版sprintf
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include "kstring.h" | |
| #include <stdio.h> | |
| static const int MAXDIGITS = 20; | |
| static const char char_table[16] | |
| = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', | |
| 'a', 'b', 'c', 'd', 'e', 'f'}; | |
| int int2str(const int n, const int x, char *str) | |
| { | |
| char buf[MAXDIGITS+2]; | |
| int i, j; | |
| int y; | |
| for(i = 0, y = x > 0? x : -x; (i < MAXDIGITS) && (y != 0); ++i, y = y /n) { | |
| buf[i] = char_table[y % n]; | |
| } | |
| if(x < 0) { | |
| buf[i] = '-'; | |
| } else { | |
| i--; | |
| } | |
| for(j = 0; i >= 0; --i, ++j) { | |
| str[j] = buf[i]; | |
| } | |
| str[j] = '\0'; | |
| return j; | |
| } | |
| int uint2str(const unsigned int n, const unsigned int x, char *str) | |
| { | |
| char buf[MAXDIGITS+2]; | |
| int i, j; | |
| unsigned int y; | |
| for(i = 0, y = x; (i < MAXDIGITS) && (y != 0); ++i, y = y /n) { | |
| buf[i] = char_table[y % n]; | |
| } | |
| i--; | |
| for(j = 0; i >= 0; --i, ++j) { | |
| str[j] = buf[i]; | |
| } | |
| str[j] = '\0'; | |
| return j; | |
| } | |
| int sprint_int(char *str, const char *format, ...) | |
| { | |
| int *varg = (int*)(&format + 1); | |
| int fi, vi; | |
| char *s; | |
| for(fi = 0, vi = 0, s = str; format[fi] != '\0'; ++fi) { | |
| if(format[fi] == '%') { | |
| if(format[fi+1] == 'd') { | |
| int n = int2str(10, varg[vi], s); | |
| s = s + n; | |
| fi++; | |
| vi++; | |
| continue; | |
| } else if(format[fi+1] == 'u') { | |
| int n = uint2str(10, varg[vi], s); | |
| s = s + n; | |
| fi++; | |
| vi++; | |
| continue; | |
| } else if(format[fi+1] == 'x') { | |
| int n = uint2str(16, varg[vi], s); | |
| s = s + n; | |
| fi++; | |
| vi++; | |
| continue; | |
| } | |
| } | |
| *s = format[fi]; | |
| s++; | |
| } | |
| *s = '\0'; | |
| return 0; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
32bit用。64bitバイナリだと可変長引数の扱い方が変わるので動かない。