Dan
Dan

Reputation: 10548

Converting bitshifted numbers back to their original index

I have an Enumeration tagged with [Flags] that looks a bit like this:

    None = 1 >> 1,              // 0
    Monday = 1,                 // 1
    Tuesday = 1 << 1,           // 2
    Wednesday = 1 << 2,         // 4
    Thursday = 1 << 3,          // 8
    Friday = 1 << 4,            // 16
    Saturday = 1 << 5,          // 32
    Sunday = 1 << 6,            // 64
    FirstWeek = 1 << 7,         // 128
    SecondWeek = 1 << 8,        // 256
    ThirdWeek = 1 << 9,         // 512
    FourthWeek = 1 << 10        // 1024

If we just assume that the number we're shifting by is N, I need to be able to do this (pseudo ahead):

    function convert(MyEnum flags) {
        return flags >> n;
    }

Without knowing for definite what the value of MyEnum is. Is this possible? The reason I need the Nth index is simply because I need to be able to convert between two enums - this one, and one that isn't [Flags] tagged, but indexed 1 - 7 (for each day).

How can I do this?

Clarification: I need to be able to go from flags = ThirdWeek (equal to 1 << 9) to 10 (N (which is 9) + 1)

I solved this by doing:

 int base = (int)Math.Log((double)flags;

Upvotes: 2

Views: 122

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726939

If you know for sure that the number is a power of two, you can solve this problem by counting trailing zeros, like this:

uint v;
uint c = 32;
v &= (0-v);
if (v != 0) c--;
if ((v & 0x0000FFFF) != 0) c -= 16;
if ((v & 0x00FF00FF) != 0) c -= 8;
if ((v & 0x0F0F0F0F) != 0) c -= 4;
if ((v & 0x33333333) != 0) c -= 2;
if ((v & 0x55555555) != 0) c -= 1;

This code is taken from here.

Upvotes: 3

Dan
Dan

Reputation: 10548

Logarithms. I wish I paid more attention in math.

    None = 1 >> 1,              // 0
    Monday = 1,                 // 1
    Tuesday = 1 << 1,           // 2
    Wednesday = 1 << 2,         // 4
    Thursday = 1 << 3,          // 8
    Friday = 1 << 4,            // 16
    Saturday = 1 << 5,          // 32
    Sunday = 1 << 6,            // 64
    FirstWeek = 1 << 7,         // 128
    SecondWeek = 1 << 8,        // 256
    ThirdWeek = 1 << 9,         // 512
    FourthWeek = 1 << 10        // 1024

    function convert(MyEnum flags) {
         return Math.Log((int)flags, 2);
    }

For clarification I did actually search but I had forgotten the name of what I was trying to do.

Upvotes: 1

Related Questions