0

I have many objects in a matrix which are storing the connections to their neighbours in a single integer variable.

public static final int NONE = 0x00;
public static final int LEFT = 0x01;
public static final int TOP = 0x02;
public static final int RIGHT = 0x04;
public static final int BOTTOM = 0x08;

connections = LEFT | RIGHT | BOTTOM; // example usage

Now I want to be able to rotate certain objects by 90° CW or CCW. In the example above a clockwise rotation should be equivalent to

connections = TOP | BOTTOM | LEFT;

A left / right bitshift of 1 seems the obvious solution but I don't know how to limit the bitshift to the bits of LEFT (0x01) to BOTTOM (0x08).

I hope someone can help me. I'm lost when it comes to bit operations.

5
  • Any reason you don't want to use an enum and EnumSet instead?
    – Jon Skeet
    Oct 15, 2012 at 15:15
  • This is for performance reasons. I'm coding games for mobile platforms.
    – HD_92
    Oct 15, 2012 at 15:59
  • Have you tried using EnumSet and found it to be a bottleneck?
    – Jon Skeet
    Oct 15, 2012 at 16:01
  • No, I'm sorry. I don't know if there are larger performance improvements by using bitshift. This operation may be performed very often during gameplay for many objects (100+), so it seemed easier and faster to just use bitshift.
    – HD_92
    Oct 15, 2012 at 16:16
  • 1
    Never guess with performance. Write the cleanest code which works, test its performance, and see whether it's adequate. If it's not, then optimize until it's adequate.
    – Jon Skeet
    Oct 15, 2012 at 16:29

1 Answer 1

3

This should do it:

connections = ((connections << 1) | (connections >> 3)) & 0x0f;
1
  • Thank you! This works really great! For ccw rotation I just had to change left shift into right shift and vice versa!
    – HD_92
    Oct 15, 2012 at 15:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.