Does anyone know how to check the cpu in C# if it supports popcount(population count)? C++ is easy but trying to do some C++ to C# conversion with some chess code.
Thanks much.
Does anyone know how to check the cpu in C# if it supports popcount(population count)? C++ is easy but trying to do some C++ to C# conversion with some chess code.
Thanks much.
I have yet to find an easy way to detect and use special CPU instructions in C#. There are several options, none of them nice;
I never went that way and implemented a C# popcount;
/// <summary>
/// Count the number of bits set to 1 in a ulong
/// </summary>
public static byte BitCount(this ulong value)
{
ulong result = value - ((value >> 1) & 0x5555555555555555UL);
result = (result & 0x3333333333333333UL) + ((result >> 2) & 0x3333333333333333UL);
return (byte)(unchecked(((result + (result >> 4)) & 0xF0F0F0F0F0F0F0FUL) * 0x101010101010101UL) >> 56);
}
Welcome to Stackoverflow :) i found this question that seems to be similar to this one, perhaps you'll find it helpful as well.
Elegantly determine if more than one boolean is "true"
You can also look at the bit operators that are in c# as well as this article
-edit-
Also to awnser your question more directly, since c# is compiled to IL not to machine code, you cant really do cpu level optimizations. The JIT compiler in the common language runtime is able to do some optimization when the code is actually run, but there is no direct access to that process from the language itself.
You can however mix c++ and managed code and do your low level optimizations there, but it kind of defeats the purpose of moving to c#