- Home /
Bitwise & Operator in Shaders?
My question is how can I emulate a bitwise & operator in a shader? I have a line of code that is basically:
int a = i & 255;
(where i can become a relatively large number) in a C# script and I need it to work identically in a shader. How can I emulate this operator in a shader?
Answer by _Gkxd · Jul 11, 2015 at 06:07 AM
The last time I checked, bitwise operators aren't available in CG. See the description of table 3-2 on this page:
Table 3-2 presents the complete list of operators, along with their precedence, associativity, and usage. Operators marked with a reverse highlight are currently reserved. However, no existing Cg profiles support these reserved operators because current graphics hardware does not support bitwise integer operations.
The bitwise and (&) with 255 is equivalent to modding (%) with 256 though, so you can use that instead.
Well I did say "emulate" - I knew they weren't available so I was wondering how I could replicate their functionality... thanks!
After quickly testing this I realized that if "a" (in the example in the OP) is negative then modding and the bitwise & are no longer returning the same number... how can I fix that?
Ah, I didn't think that you'd have negatives.
x = ((x % 256) + 256) % 256
would work with negatives. If you know that your number doesn't go below -256, then you can use x = (x + 256) % 256
ins$$anonymous$$d.
You might also be able to make the number unsigned
... it seems that they exist in Cg: http://http.developer.nvidia.com/Cg/Cg_language.html
Actually, now that I think about it, you can probably just use unsigned chars and completely ignore bitwise operators/modding, since integer overflow for unsigned chars would keep the value between 0 and 255.
Your answer
Follow this Question
Related Questions
What is the difference between these ? 1 Answer
Shader setting integer 1 Answer
Can't use "Integer" type in Shader property? 0 Answers
Bitwise Operators 3 Answers
Bitwise operations in hlsl, is there an alternative method? 1 Answer