2

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
    In general you don't want to do this; GPUs tend to be weak at integer bit mangling, and forcing the GPU to do this for millions of fragments, or tens of thousands of vertices is normally a bad idea from a performance point of view. – solidpixel Jan 30 '17 at 15:25

3 Answers3

2

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.

Tommy
  • 99,986
  • 12
  • 185
  • 204
  • 1
    if you want another bit than the third change 8.0 to 2^position. e.g: 2^4=16.0 for the fourth bit ... – walox Mar 31 '20 at 10:32
1

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;
}
Mortennobel
  • 3,383
  • 4
  • 29
  • 46
-3
int GetBitOnLocation(int value, int location)
{
    int myBit = value & (1 << location);
    if (myBit == 0)
        return 0;
    else
        return 1;
}