Created
January 10, 2023 19:12
-
-
Save Kittoes0124/e343ab48fbac9335e0dea963b6a18a0c to your computer and use it in GitHub Desktop.
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
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