Created
December 7, 2010 16:32
-
-
Save tomas-stefano/732007 to your computer and use it in GitHub Desktop.
Integer to char in C (with long long support)
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
| void integer_to_char(long long value, char* str, int base) { | |
| static char num[] = "0123456789abcdefghijklmnopqrstuvwxyz"; | |
| char *wstr = str; | |
| int sign; | |
| lldiv_t res; | |
| // Validate base | |
| if (base < 2 || base > 35) { | |
| *wstr = '\0'; | |
| return; | |
| } | |
| // Take care of sign | |
| if ((sign = value) < 0) value = -value; | |
| // Conversion. Number is reversed. | |
| do { | |
| res = lldiv(value, base); | |
| *wstr++ = num[res.rem]; | |
| } while((value = res.quot)); | |
| if(sign < 0) *wstr ++='-'; | |
| *wstr='\0'; | |
| // Reverse string | |
| reverse_string(str, wstr-1); | |
| } | |
| /* | |
| * Return a string reverse | |
| */ | |
| void reverse_string(char* begin, char* end) { | |
| char aux; | |
| while(end > begin) aux=*end, *end--=*begin, *begin++=aux; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment