Skip to content

Instantly share code, notes, and snippets.

@pasberth
Created January 2, 2012 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pasberth/1549905 to your computer and use it in GitHub Desktop.
Save pasberth/1549905 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <math.h>
void int2str(long, char *);
int main(int argc, char *argv[])
{
long i = 12345;
char str[] = "00000\0";
int2str(i, str);
puts(str);
return 0;
}
void int2str(long n, char *str)
{
int len = strlen(str);
int i;
for( i = 0; i < len; i++ )
{
long mask = pow(10, i+1); /* マスクする値。12345を10で割れば5が得れるし100で割れば45が得れる */
int a = (n % mask) / pow(10, i); /* マスクしたものが45なら10で割って4を、345なら100で割って3を得る */
char c = (char)(a + (unsigned short)'0'); /* '0'..'9'は連番なので、 N+'0'で'N'になる */
str[len-i-1] = c; /* 下の桁から順番に代入する */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment