Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit 137eb1c

Browse files
committed
Add fast ToHex ext method
1 parent 4530596 commit 137eb1c

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/ServiceStack.Text/StringExtensions.cs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1242,6 +1242,31 @@ public static T FromXml<T>(this string json)
12421242
}
12431243
#endif
12441244

1245+
public static string ToHex(this byte[] hashBytes, bool upper=false)
1246+
{
1247+
var len = hashBytes.Length * 2;
1248+
var chars = new char[len];
1249+
var i = 0;
1250+
var index = 0;
1251+
for (i = 0; i < len; i += 2)
1252+
{
1253+
var b = hashBytes[index++];
1254+
chars[i] = GetHexValue(b / 16, upper);
1255+
chars[i + 1] = GetHexValue(b % 16, upper);
1256+
}
1257+
return new string(chars);
1258+
}
1259+
1260+
private static char GetHexValue(int i, bool upper)
1261+
{
1262+
if (i < 0 || i > 15)
1263+
throw new ArgumentOutOfRangeException(nameof(i), "must be between 0 and 15");
1264+
1265+
return i < 10
1266+
? (char) (i + '0')
1267+
: (char) (i - 10 + (upper ? 'A' : 'a'));
1268+
}
1269+
12451270
}
12461271
}
12471272

0 commit comments

Comments
 (0)