Skip to content

Instantly share code, notes, and snippets.

@Kittoes0124
Created January 10, 2023 19:12
Show Gist options
  • Save Kittoes0124/e343ab48fbac9335e0dea963b6a18a0c to your computer and use it in GitHub Desktop.
Save Kittoes0124/e343ab48fbac9335e0dea963b6a18a0c to your computer and use it in GitHub Desktop.
public static T SetLeastSignificantBits<T>(this T value) where T : IBinaryInteger<T>, IUnsignedNumber<T> {
var x = (value | (value >> 1));
x |= (x >> 2);
x |= (x >> 4);
if (BinaryIntegerConstants<T>.Size > T.CreateChecked(value: 8UL)) {
x |= (x >> 8);
}
if (BinaryIntegerConstants<T>.Size > T.CreateChecked(value: 16UL)) {
x |= (x >> 16);
}
if (BinaryIntegerConstants<T>.Size > T.CreateChecked(value: 32UL)) {
x |= (x >> 32);
}
if (BinaryIntegerConstants<T>.Size > T.CreateChecked(value: 64UL)) {
x |= (x >> 64);
}
if (BinaryIntegerConstants<T>.Size > T.CreateChecked(value: 128UL)) {
var i = int.CreateChecked(value: (BinaryIntegerConstants<T>.Size >> 1));
do {
x |= (x >> i);
} while ((i >>= 1) > 128);
}
return x;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment