0

I have an enum with flags setup for my grid system:

[Flags]
public enum GridNeighbours
{
    North = 1,
    NorthEast = 2,
    East = 4,
    SouthEast = 8,
    South = 16,
    SouthWest = 32,
    West = 64,
    NorthWest = 128
}

But i want to also access them by index so if i want the index of say East, i would get [2] not 4.

Casting to int doesn't do the job as that just gives the flag number which i am not looking for.

Is there a way to do that at all ?

WDUK
  • 1,412
  • 1
  • 12
  • 29
  • 1
    each flag has only 1 bit set so in this case you just need to use [`BitOperations.TrailingZeroCount((int)enumValue)`](https://learn.microsoft.com/en-us/dotnet/api/system.numerics.bitoperations.trailingzerocount?view=netcore-3.0) – phuclv Aug 22 '20 at 04:50
  • @phuclv oh nice :) Do you happen to know the source code of how it is actually done? – WDUK Aug 23 '20 at 05:37
  • it's an intrinsic that maps directly or indirectly to the machine instruction like x86's TZCNT/BSF or ARM's CLZ and probably a fallback version for architectures without those instructions. Check [dotnet's repo on github](https://github.com/search?l=C%23&q=org%3Adotnet+TrailingZeroCount&type=Code) and see – phuclv Aug 23 '20 at 05:57
  • @phuclv the reason i ask is i can't use core for my unity they use .NET 4.x so the class is not available for me :( – WDUK Aug 23 '20 at 18:01
  • if .NET Core is not available then you must implement it yourself: [What's the quickest way to compute log2 of an integer in C#?](https://stackoverflow.com/q/8970101/995714), [Fastest implementation of log2(int) and log2(float)](https://stackoverflow.com/q/15967240/995714), [Fast way of finding most and least significant bit set in a 64-bit integer](https://stackoverflow.com/q/31374628/995714) – phuclv Aug 24 '20 at 01:49

0 Answers0