Skip to content

Instantly share code, notes, and snippets.

@sapphire-al2o3
Last active October 22, 2020 02:20
Show Gist options
  • Save sapphire-al2o3/875f4c872fd4cad3540aa3ee81521111 to your computer and use it in GitHub Desktop.
Save sapphire-al2o3/875f4c872fd4cad3540aa3ee81521111 to your computer and use it in GitHub Desktop.
int.ToString("0000")の置き換え
public static class IntToStringUtil
{
public static string Padding0(int n, int d)
{
char[] c = new char[n < 0 ? d + 1 : d];
int s = 0;
if (n < 0)
{
c[0] = '-';
n *= -1;
s = 1;
}
for (int i = d + s - 1; i >= s; i--)
{
if (n > 0)
{
c[i] = (char)(n % 10 + '0');
n /= 10;
}
else
{
c[i] = '0';
}
}
return new string(c);
}
}
public static class UnsafeIntToStringUtil
{
public static string Padding0(int n, int d)
{
unsafe
{
char* c = stackalloc char[11];
int s = 0;
if (n < 0)
{
c[0] = '-';
n *= -1;
s = 1;
}
for (int i = d + s - 1; i >= s; i--)
{
if (n > 0)
{
c[i] = (char)(n % 10 + '0');
n /= 10;
}
else
{
c[i] = '0';
}
}
return new string(c, 0, d + s);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment