Bitwise operations in shaders

If I can make bitwise operations to work, I would really speed up my shader. I’ve found out that bitwise operations don’t work in CG, but they work perfectly fine when compiling to GLSL.

Is there a way to make them work in CG?

Thanks!

one way to do them in a shader is by using a lookup texture, a 256x256 texture would give you ability to work with 1 byte (0-255)

	public static void TextureFunc( Texture2D tex )
	{
		for ( int y = 0; y<tex.height; ++y )
		{
			for ( int x = 0; x<tex.width; ++x )
			{
				byte b = (byte)((int)x(int)y); //the  here is AND operator,  could be ^ for XOR.. etc
				Color c = new Color32(b,b,b,0xff);
				tex.SetPixel(x, y, c);
			}
		}
	}

	public static Texture2D lookupTexture;
	public static void GenerateLookupTexture (int width, int height)
	{
		Texture2D tex;
		if ( lookupTexture  lookupTexture.width == width  lookupTexture.height == height )
		{
			tex = lookupTexture;
		}
		else
		{
			tex = new Texture2D(width, height, TextureFormat.ARGB32, false);
		}
		
		TextureFunc(tex);
		tex.Apply();
		tex.wrapMode = TextureWrapMode.Clamp;
		tex.filterMode = FilterMode.Point;
	
		if (lookupTexture != tex)
		{
			DestroyImmediate (lookupTexture);
		}
		lookupTexture = tex;
		
	    byte[] bytes = tex.EncodeToPNG();
	    
		System.IO.File.WriteAllBytes(Application.dataPath + "/BitwiseLUT.png", bytes);
	}

in the shader you’d supply the generated BitwiseLUT.png and the bitwise operation would be looked up by UV coordinates, the X and Y being the two values you’re working with in the shader

float result = tex2D(_XORlut, float2(val1, val2)).r;

1 Like

Thanks for your answer!
Unfortunately it won’t work because I need to work with really large integers, up to 2^28.

But thanks anyways!