Question

I have the following code which converts a set of 9 booleans into an int for me, which I'm using for a tilemap sprite array to quickly find the tiles. Just curious, is there a simple way of reversing this?

i.e. if all the bool's are true, the result below would be 511. Is there an easy way to convert that back to assign the booleans all true? Or another example, a is false, the rest are true, result would be 510. How can I convert that back to a = true and the rest false?

int GetBitmask(bool a, bool b, bool c, bool d, bool e, bool f, bool g, bool h, bool i)
{
    int r = (a ? 1 << 0 : 0) | (b ? 1 << 1 : 0) | (c ? 1 << 2 : 0) |
            (d ? 1 << 3 : 0) | (e ? 1 << 4 : 0) | (f ? 1 << 5 : 0) |
            (g ? 1 << 6 : 0) | (h ? 1 << 7 : 0) | (i ? 1 << 8 : 0);
    return r;
}
Was it helpful?

Solution

You want to use logical AND (&) to mask out your answers, and reverse the way you made r:

a = (r & (1 << 0)) != 0;
b = (r & (1 << 1)) != 0;
c = (r & (1 << 2)) != 0;
d = (r & (1 << 3)) != 0;
e = (r & (1 << 4)) != 0;
f = (r & (1 << 5)) != 0;
g = (r & (1 << 6)) != 0;
h = (r & (1 << 7)) != 0;
i = (r & (1 << 8)) != 0;

What this does:

say r was = 14 (i.e. b, c, and d were true). Then the bits of r are

00000000 00000000 00000000 00001110

For a, 1 << 0 = 1, so take those bits and AND it with

00000000 00000000 00000000 00000001

The result for a is 0 so the bool should be false.

For b, 1 << 1 = 2, so take the bits of r and AND it with

00000000 00000000 00000000 00000010

You see there's 1 bit in common, so the result of ANDing it is 2, so it's true.

OTHER TIPS

It may not be any faster than your method, but you could use a little Linq:

int GetBitmask(params bool[] bits)
{
    return bits.Select((b, i) => b ? 1 << i : 0).Aggregate((a, b) => a | b);
}

And to convert it back:

bool[] GetBools(int mask)
{
    return Enumerable.Range(0, 9).Select(b => (mask & (1 << b)) != 0).ToArray();
}

Just do the reverse.

bool[] GetBooleans( int input )
{
    bool[] ret = new bool[9];
    while( int i = 0; i < 9; ++i )
        bool[i] = (input >> i) & 1;
    return ret;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top