I've been using LWJGL for some graphics work. I am unsure how excatly the bitwise operator works. I want to mimic the OpenGL bit flags and check it with an if statement using the |
bitwise operator.
I would like to reproduce this behaviorglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
How can I use an if statement to check if GL_COLOR_BUFFER_BIT
is used and another to check if GL_DEPTH_BUFFER_BIT
is used.
Use this:
if ((myFlags & GL_COLOR_BUFFER_BIT) == GL_COLOR_BUFFER_BIT)
// flag is set, act accordingly
Note the parens: necessary since bitwise &
has a lower precedence than ==
.
Now, why this works... Let us take an hypothetical example:
public static final int TEST = 0x4;
// TEST: 0000 0000 0000 0000 0000 0000 0000 0100
value = 35;
// value: 0000 0000 0000 0000 0000 0000 0010 0011
final boolean b1 = (value & TEST) == TEST; // FALSE
value = 70;
// value: 0000 0000 0000 0000 0000 0000 0100 0110
final boolean b1 = (value & TEST) == TEST; // TRUE
Note that in Java, such practices are generally seldomly used; you would generally prefer using an Enum
instead; however, curiously there doesn't seem to be a "Do It The Java Way(tm)" API for OpenGL... All existing APIs seem to fall short of what is commonly used or, if they don't use it on purpose, do not document it :/