Skip to content

Instantly share code, notes, and snippets.

@anarazel anarazel/ltoa.c
Created Feb 4, 2019

Embed
What would you like to do?
void
pg_ltoa(int32 val, char *a)
{
uint32 value;
/*
* Avoid problems with the most negative integer not being representable
* as a positive integer.
*/
if (unlikely(val == PG_INT32_MIN))
{
memcpy(a, "-2147483648", 12);
return;
}
if (val < 0)
{
value = -val;
*a++ = '-';
}
else
value = val;
if (value < 10)
{
a[0] = '0' + value;
a[1] = '\0';
}
else if (value < 100)
{
a[0] = '0' + (value / 10);
a[1] = '0' + (value % 10);
a[2] = '\0';
}
else if (value < 1000)
{
a[0] = '0' + (value / 100);
a[1] = '0' + (value % 100) / 10;
a[2] = '0' + (value % 10) / 1;
a[3] = '\0';
}
else if (value < 10000)
{
a[0] = '0' + (value / 1000);
a[1] = '0' + (value % 1000) / 100;
a[2] = '0' + (value % 100) / 10;
a[3] = '0' + (value % 10) / 1;
a[4] = '\0';
}
else if (value < 100000)
{
a[0] = '0' + (value / 10000);
a[1] = '0' + (value % 10000) / 1000;
a[2] = '0' + (value % 1000) / 100;
a[3] = '0' + (value % 100) / 10;
a[4] = '0' + (value % 10) / 1;
a[5] = '\0';
}
else if (value < 1000000)
{
a[0] = '0' + (value / 100000);
a[1] = '0' + (value % 100000) / 10000;
a[2] = '0' + (value % 10000) / 1000;
a[3] = '0' + (value % 1000) / 100;
a[4] = '0' + (value % 100) / 10;
a[5] = '0' + (value % 10) / 1;
a[6] = '\0';
}
else if (value < 10000000)
{
a[0] = '0' + (value / 1000000);
a[1] = '0' + (value % 1000000) / 100000;
a[2] = '0' + (value % 100000) / 10000;
a[3] = '0' + (value % 10000) / 1000;
a[4] = '0' + (value % 1000) / 100;
a[5] = '0' + (value % 100) / 10;
a[6] = '0' + (value % 10) / 1;
a[7] = '\0';
}
else if (value < 100000000)
{
a[0] = '0' + (value / 10000000);
a[1] = '0' + (value % 10000000) / 1000000;
a[2] = '0' + (value % 1000000) / 100000;
a[3] = '0' + (value % 100000) / 10000;
a[4] = '0' + (value % 10000) / 1000;
a[5] = '0' + (value % 1000) / 100;
a[6] = '0' + (value % 100) / 10;
a[7] = '0' + (value % 10) / 1;
a[8] = '\0';
}
else if (value < 1000000000)
{
a[0] = '0' + (value / 100000000);
a[1] = '0' + (value % 100000000) / 10000000;
a[2] = '0' + (value % 10000000) / 1000000;
a[3] = '0' + (value % 1000000) / 100000;
a[4] = '0' + (value % 100000) / 10000;
a[5] = '0' + (value % 10000) / 1000;
a[6] = '0' + (value % 1000) / 100;
a[7] = '0' + (value % 100) / 10;
a[8] = '0' + (value % 10) / 1;
a[9] = '\0';
}
else
{
a[0] = '0' + (value / 1000000000);
a[1] = '0' + (value % 1000000000) / 100000000;
a[2] = '0' + (value % 100000000) / 10000000;
a[3] = '0' + (value % 10000000) / 1000000;
a[4] = '0' + (value % 1000000) / 100000;
a[5] = '0' + (value % 100000) / 10000;
a[6] = '0' + (value % 10000) / 1000;
a[7] = '0' + (value % 1000) / 100;
a[8] = '0' + (value % 100) / 10;
a[9] = '0' + (value % 10) / 1;
a[10] = '\0';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.