Skip to content

Instantly share code, notes, and snippets.

@RonenNess
Created December 19, 2021 22:34
Show Gist options
  • Save RonenNess/580baae505622562fe476947d869dbd0 to your computer and use it in GitHub Desktop.
Save RonenNess/580baae505622562fe476947d869dbd0 to your computer and use it in GitHub Desktop.
Misc string related utils for C#, including deterministic hash method.
/// <summary>
/// String-related utils.
/// </summary>
public static class StringUtils
{
/// <summary>
/// Convert string to bytes[].
/// </summary>
/// <param name="str">String to convert.</param>
/// <returns>String as bytes[].</returns>
public static byte[] ToBytes(string str)
{
return Encoding.UTF8.GetBytes(str);
}
/// <summary>
/// Convert string to bytes[].
/// </summary>
/// <param name="bytes">Bytes to convert.</param>
/// <param name="start">Index to start converting from.</param>
/// <param name="count">How many bytes to convert.</param>
/// <returns>String from bytes.</returns>
public static string ToString(byte[] bytes, int start = 0, int count = 0)
{
if (count == 0) { count = bytes.Length - start; }
return Encoding.UTF8.GetString(bytes, start, count);
}
/// <summary>
/// Convert bytes array to hex string.
/// </summary>
/// <param name="bytes">Bytes to convert.</param>
/// <returns>Value as hex string.</returns>
public static string ToHexString(byte[] bytes)
{
return String.Concat(Array.ConvertAll(bytes, x => x.ToString("X2")));
}
/// <summary>
/// Convert string to a string containing an MD5 hash of the source.
/// </summary>
/// <param name="source">Source string to md5.</param>
/// <returns>Hashed source as string.</returns>
public static string ToMd5String(string source)
{
using (MD5 md5Hash = MD5.Create())
{
return ToString(md5Hash.ComputeHash(ToBytes(source)));
}
}
/// <summary>
/// Convert string to a hex string containing a SHA256 hash of the source.
/// </summary>
/// <param name="source">Source string to SHA256.</param>
/// <returns>Hashed source as hex string.</returns>
public static string ToSha256Hex(string source)
{
using (SHA256 sha256Hash = SHA256.Create())
{
return ToHexString(sha256Hash.ComputeHash(ToBytes(source)));
}
}
/// <summary>
/// Method to get deterministic hash code from string.
/// </summary>
public static int GetDeterministicHashCode(this string str)
{
unchecked
{
int hash1 = (5381 << 16) + 5381;
int hash2 = hash1;
for (int i = 0; i < str.Length; i += 2)
{
hash1 = ((hash1 << 5) + hash1) ^ str[i];
if (i == str.Length - 1)
break;
hash2 = ((hash2 << 5) + hash2) ^ str[i + 1];
}
return hash1 + (hash2 * 1566083941);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment