1

I have a flag enum array that I create and store in the database with my program as a numeric value. Is there anyway with a Postgres function to check for whether or not a specific bit is set?

So it would be:

value1 = 1
value2 = 2
vaule3 = 4
....
value10 = 512

I want to check that 534 has the value2 flag. Is that possible?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228

1 Answers1

1

Yes, there is the very convenient "bitwise AND" operator & for integer numbers:

SELECT 534 & value2 = value2;

When logically "anded" with a power of 2 the same power of 2 is returned if the bit is set. (Since every power of 2 is represented by a distinct bit in the binary representation of a positive integer number.) Else you get 0. Compare the result with the value itself and you get either TRUE or FALSE. Voilá.

Related:

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
  • That's awesome! That's so simple... I'm a little ashamed of myself for not being able to find that lol, I guess my terms used in google just didn't produce the results I needed. Thank you. – Travis Lange Feb 27 '18 at 15:01