How to get a bit from a integer using GLSL and OpenGL ES 2.0

半世苍凉 提交于 2020-04-11 17:26:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!