Skip to content

Instantly share code, notes, and snippets.

@xoofx
Created June 5, 2016 23:29
Show Gist options
  • Save xoofx/bd7c06f707013514fd1d02c025472cbd to your computer and use it in GitHub Desktop.
Save xoofx/bd7c06f707013514fd1d02c025472cbd to your computer and use it in GitHub Desktop.
Convert an integer to a string IP address
// Follow up of the discussion https://twitter.com/stebets/status/739563007202758656
public static unsafe string IntegerToIPAddress(uint input)
{
var text = stackalloc char[15];
var ptext = text + 15;
for (int i = 0; i < 4; i++)
{
if (i > 0)
{
*--ptext = '.';
}
var value = input & 0xFF;
input = input >> 8;
var index = value >= 100 ? 2 : value >= 10 ? 1 : 0;
while (index >= 0)
{
*--ptext = (char)('0' + (value % 10));
value = value / 10;
index--;
}
}
return new string(ptext, 0, 15 - (int)(ptext - text));
}
// Method | Median | StdDev | Gen 0 | Gen 1 | Gen 2 | Bytes Allocated/Op |
// ------------------------ |------------ |---------- |--------- |------ |------ |------------------- |
// BenchIP2LocationHelper7 | 181.6422 ns | 2.3263 ns | 1,222.71 | - | - | 60.24 |
// BenchIP2Locationxoofx | 95.9410 ns | 0.7456 ns | 278.00 | - | - | 14.06 |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment