Created
June 6, 2016 04:39
-
-
Save xoofx/00ec52acc26f100bfadc8910140085f9 to your computer and use it in GitHub Desktop.
Convert IP integer address to a string
This file contains 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
// Follow up of https://twitter.com/stebets/status/739563007202758656 | |
private static readonly string[] ByteToString = Enumerable.Range(0, 256).Select(x => x.ToString()).ToArray(); | |
public unsafe static string FastIntegerToIPAddress2(uint input) | |
{ | |
// t3.t2.t1.t0 | |
var t0 = ByteToString[input & 0xFF]; | |
input = input >> 8; | |
var t1 = ByteToString[input & 0xFF]; | |
input = input >> 8; | |
var t2 = ByteToString[input & 0xFF]; | |
input = input >> 8; | |
var t3 = ByteToString[input & 0xFF]; | |
var value = new string('\0', t0.Length + t1.Length + t2.Length + t3.Length + 3); | |
fixed (char* t = value) | |
{ | |
var ptr = t; | |
foreach (var c in t3) *ptr++ = c; | |
*ptr++ = '.'; | |
foreach (var c in t2) *ptr++ = c; | |
*ptr++ = '.'; | |
foreach (var c in t1) *ptr++ = c; | |
*ptr++ = '.'; | |
foreach (var c in t0) *ptr++ = c; | |
} | |
return value; | |
} | |
// Method | Median | StdDev | Gen 0 | Gen 1 | Gen 2 | Bytes Allocated/Op | | |
// ----------------------------- |----------- |---------- |--------- |------ |------ |------------------- | | |
// BenchFastIntegerToIPAddress | 23.7875 ns | 0.2003 ns | 1,131.00 | - | - | 14.40 | | |
// BenchFastIntegerToIPAddress2 | 19.7718 ns | 0.2177 ns | 1,139.00 | - | - | 14.40 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment