Added methods for counting the number of bits set in integers

git-svn-id: file:///srv/devel/repo-conversion/nusu@210 d2e56fa2-650e-0410-a79f-9358c0239efd
This commit is contained in:
Markus Ewald 2010-11-22 18:05:55 +00:00
parent 22cea75a7a
commit 645148a751
2 changed files with 73 additions and 2 deletions

View file

@ -37,7 +37,7 @@ namespace Nuclex.Support {
/// <param name="value">Value of which to return the next highest power of 2</param>
/// <returns>The next highest power of 2 to the value</returns>
public static ulong NextPowerOf2(this ulong value) {
if(value == 0)
if (value == 0)
return 1;
--value;
@ -63,7 +63,7 @@ namespace Nuclex.Support {
/// <param name="value">Value of which to return the next highest power of 2</param>
/// <returns>The next highest power of 2 to the value</returns>
public static uint NextPowerOf2(this uint value) {
if(value == 0)
if (value == 0)
return 1;
--value;
@ -77,6 +77,52 @@ namespace Nuclex.Support {
return value;
}
/// <summary>Returns the number of bits set in an </summary>
/// <param name="value">Value whose bits will be counted</param>
/// <returns>The number of bits set in the integer</returns>
public static int CountBits(this int value) {
return CountBits((uint)value);
}
/// <summary>Returns the number of bits set in an unsigned integer</summary>
/// <param name="value">Value whose bits will be counted</param>
/// <returns>The number of bits set in the unsigned integer</returns>
/// <remarks>
/// Based on a trick revealed here:
/// http://stackoverflow.com/questions/109023
/// </remarks>
public static int CountBits(this uint value) {
value = value - ((value >> 1) & 0x55555555);
value = (value & 0x33333333) + ((value >> 2) & 0x33333333);
return (int)unchecked(
((value + (value >> 4) & 0xF0F0F0F) * 0x1010101) >> 24
);
}
/// <summary>Returns the number of bits set in a long integer</summary>
/// <param name="value">Value whose bits will be counted</param>
/// <returns>The number of bits set in the long integer</returns>
public static int CountBits(this long value) {
return CountBits((ulong)value);
}
/// <summary>Returns the number of bits set in an unsigned long integer</summary>
/// <param name="value">Value whose bits will be counted</param>
/// <returns>The number of bits set in the unsigned long integer</returns>
/// <remarks>
/// Based on a trick revealed here:
/// http://stackoverflow.com/questions/2709430
/// </remarks>
public static int CountBits(this ulong value) {
value = value - ((value >> 1) & 0x5555555555555555UL);
value = (value & 0x3333333333333333UL) + ((value >> 2) & 0x3333333333333333UL);
return (int)unchecked(
(((value + (value >> 4)) & 0xF0F0F0F0F0F0F0FUL) * 0x101010101010101UL) >> 56
);
}
}
} // namespace Nuclex.Support