Search code examples
javaarrayslistlibgdxswitch-statement

How can I correctly do a binary switch statement in java?


I am working on a game and I need to convert my binary tile id set into a switch statement so I can grab the correct tile from the sprite sheet.

I need to convert this list which contains all the possible tiles I would need from 255 to just 48 or so Tiles into a integer that I can use to get my tile id.

Can I get some help on starting this statement?

Also a x means that it doesn't matter what bit is set there.

EDIT: Should also say that this is a 8 bit number DCBA4321

enter image description here


Solution

  • I'd recomment to create a static array of 256 values for each possible combination like this:

    static final int[] DCBA4321_TO_VALUE = {
        // 0000
        47, 44, 36,343, 37, 14, 35, 32, 45, 34, 15, 40, 42, 41, 33, 38,
        // 0001
        28, 28, 27, 27, 26, 26, 23, 23, 28, 28, 27, 27, 26, 26, 23, 23, 
        // 0010
        21, 21, 21, 21, 24, 24, 24, 24, 16, 16, 16, 16, 30, 30, 30, 30,
        // 0011
         1,  1,  1,  1,  3,  3,  3,  3,  1,  1,  1,  1,  3,  3,  3,  3, 
        ...
    };
    

    Having such array you can simply join your DCBA and 4321 values using bitwise shift and add and map it to value. This seems to be the fastest approach for me

    int getValue(int DCBA, int num) {
        return DCBA4321_TO_VALUE[(DCBA << 4)+num];
    }