Skip to content

Instantly share code, notes, and snippets.

View macklinb's full-sized avatar

Macklin macklinb

View GitHub Profile
@macklinb
macklinb / GetHashCode.cs
Last active April 29, 2024 18:33
.NET's String.GetHashCode in C# and JavaScript
// .NET 3.5 implementation
public int GetHashCodeDotNet35(string str)
{
int hashCode = 0;
foreach (char ch in str)
{
hashCode = (hashCode << 5) - hashCode + (int)ch;
}
return hashCode;
}
@macklinb
macklinb / Unity-XORShift.md
Created February 25, 2021 11:26
C# implementation of UnityEngine.Random with (almost) 1-to-1 parity

This is a partial C# implementation of UnityEngine.Random with (almost) 1-to-1 parity.

Unity uses Xorshift for psuedorandom number generation. In particular Xorshift128, which uses a state consisting of four unsigned 32-bit integer values. The state is initialized in UnityEngine.Random.InitState using a signed 32-bit integer seed, which is shuffled around with a technique similar to the way a Mersenne Twister is initialized.

This has been tested as far back as Unity 4.7.0f1, and as recent as Unity 2020.1.17f1.

Notes

  • Huge thanks to MoatShrimp for figuring out how Unity initializes the Xorshift state parameters in InitState, and floating point generation.
  • C# - As below. Values may differ in .NET 5.0, but thankfully Unity doesn't yet support that.
  • JavaScript - Check out MoatShrimp's JS implemention (and neat Undermine loot lookup tool) here: