问题
I have an integer value and want to get the Bit which is placed on a special location. I'm working with GLSL for OpenGL ES 2.0
Something like this:
GetBitOnLocation(int value, int location)
{
bit myBit = value[location];
if (myBit == 0)
return 0;
if (myBit == 1)
return 1;
}
回答1:
As per the previous comments, don't do this.
ES 2 hardware needn't natively support integers; it is permitted to emulate them as floating point. To permit that, direct bit tests aren't defined.
If you're absolutely desperate, use a mod
and a step
. E.g. to test the third bit of the integer value
:
float bit = step(0.5, mod(float(value) / 8.0, 1.0));
// bit is now 1.0 if the lowest bit was set, 0.0 otherwise
The logic being to shuffle the bit you want to test into the 0.5
position then cut off all bits above it with the mod
. Then the value you have can be greater than or equal to 0.5
only if the bit you wanted was set.
回答2:
Here is a solution using integer math (note: negative integers not supported)
// 2^x
int pow2(int x){
int res = 1;
for (int i=0;i<=31;i++){
if (i<x){
res *= 2;
}
}
return res;
}
// a % n
int imod(int a, int n){
return a - (n * (a/n));
}
// return true if the bit at index bit is set
bool bitInt(int value, int bit){
int bitShifts = pow2(bit);
int bitShiftetValue = value / bitShifts;
return imod(bitShiftetValue, 2) > 0;
}
回答3:
int GetBitOnLocation(int value, int location)
{
int myBit = value & (1 << location);
if (myBit == 0)
return 0;
else
return 1;
}
来源:https://stackoverflow.com/questions/41933416/how-to-get-a-bit-from-a-integer-using-glsl-and-opengl-es-2-0