Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
In absence of bitwise operators in WebGL 1.0, I used these methods as substitute.
// CAUTION / / / CAUTION / / / CAUTION / / / CAUTION / / / CAUTION / / / CAUTION / / / CAUTION / / /
// Notice the for loops have a hardcoded values for how far they can go (32)
// This is a result of WEBGL not allowing while loops. Change the value to what you find appropriate!
// CAUTION / / / CAUTION / / / CAUTION / / / CAUTION / / / CAUTION / / / CAUTION / / / CAUTION / / /
//
// Hopefully this gives you the format for making your own operators such as XOR, NAND, etc.
//
// Adapted from this thread:
// https://scratch.mit.edu/discuss/topic/97026/
int OR(int n1, int n2){
float v1 = float(n1);
float v2 = float(n2);
int byteVal = 1;
int result = 0;
for(int i = 0; i < 32; i++){
bool keepGoing = v1>0.0 || v2 > 0.0;
if(keepGoing){
bool addOn = mod(v1, 2.0) > 0.0 || mod(v2, 2.0) > 0.0;
if(addOn){
result += byteVal;
}
v1 = floor(v1 / 2.0);
v2 = floor(v2 / 2.0);
byteVal *= 2;
} else {
return result;
}
}
return result;
}
int AND(int n1, int n2){
float v1 = float(n1);
float v2 = float(n2);
int byteVal = 1;
int result = 0;
for(int i = 0; i < 32; i++){
bool keepGoing = v1>0.0 || v2 > 0.0;
if(keepGoing){
bool addOn = mod(v1, 2.0) > 0.0 && mod(v2, 2.0) > 0.0;
if(addOn){
result += byteVal;
}
v1 = floor(v1 / 2.0);
v2 = floor(v2 / 2.0);
byteVal *= 2;
} else {
return result;
}
}
return result;
}
int RShift(int num, float shifts){
return int(floor(float(num) / pow(2.0, shifts)));
}
@chinedufn

This comment has been minimized.

Copy link

@chinedufn chinedufn commented Sep 13, 2020

Thank you!

For anyone that wants to avoid one of the if statement, here's an example & operator for 16 bit integers:

int AND_16(int n1, int n2) {
    float v1 = float(n1);
    float v2 = float(n2);

    int byte_val = 1;
    int result = 0;

    for (int i = 0; i < 16; i++){
        if (v1 == 0.0 || v2 == 0.0) {
            return result;
        }

        int both_bytes_1 = int(min(
         mod(v1, 2.0),
         mod(v2, 2.0)
        ));

        result += both_bytes_1 * byte_val;

        v1 = floor(v1 / 2.0);
        v2 = floor(v2 / 2.0);

        byte_val *= 2;
    }

    return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.