11

How do I perform bit operations in glsl?

Using the regular C style bitwise operators |, &, ^, or ! does not work.

P.T.
  • 24,557
  • 7
  • 64
  • 95
GameFreak
  • 2,881
  • 7
  • 34
  • 38

2 Answers2

9

They have been introduced with GLSL 1.30 (OGL 3.0).

Depending on what you want to do, you could eventually emulate them with floating point operations, x & (2^n)-1 = frac(x/(2^n))*(2^n) for example, but you'll have to take care of floating point errors.

Nathan Monteleone
  • 5,430
  • 29
  • 43
Aszarsha
  • 369
  • 2
  • 5
  • Are there more examples like that? This AND operation is what I needed the most, but also some OR would come in handy... – St0fF Nov 27 '17 at 14:00
  • @St0fF If you can find a way to do `¬` (not gate) then you can combine it with `∧` (and gate) using DeMorgan's law to obtain `p ∨ q = ¬( ¬p ∧ ¬q )`. –  Sep 26 '19 at 08:22
8

You need to put either

#version 130

or

#extension GL_EXT_gpu_shader4 : enable

in the top of your shader to get access to the bit operators

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226