• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 313
  • Last Modified:

Postgres and bitwise operator

I am trying to figure out how to check a column in my database to see if a bit is on or off. I have a bigint column that actually right now only represents 8 values or bits. What I need to do is check to see if the 5th value or 5th bit in this column is on or off. I have written one select statement that will give me everything up to the 5th bit but if the 6,7,and 8th bits are on with the 5th it ignores the count on those values. Here is my query:

select * from sometable where bigintcolumn >> 5=1;

Like I stated above this works fine until I have the 5th bit on with a bit from position 6 or greater on also. It will ignore these values. I guess I may be truncating everything past the 5th bit position in my query above.
0
phil435
Asked:
phil435
  • 3
  • 2
2 Solutions
 
Daniel WilsonCommented:
So you need to isolate that 5th bit ...
Consulting this ... http://www.postgresql.org/docs/8.0/interactive/functions-math.html ...
what about


select * from sometable where bigintcolumn & (2 << 4)=1;

Open in new window

0
 
phil435Author Commented:
Ok with a little modification that works depending on if you start your bit position from 0 or 1 :) You need to say

select * from sometable where bigintcolumn & (2 << 4)=32 or
select * from sometable where bigintcolumn & (1 << 5)=32
Also couldnt  use =1 since that bits value was 32
You are starting from 0000 0010 and moving to 0010 0000

Also found that this works:

select * from sometable where 32 & bigintcolumn = 32

Thanks for the help
0
 
Daniel WilsonCommented:
Glad to help.  Now that you post the correction I see where I wasn't quite right ... should have seen it the first time!
0
 
phil435Author Commented:
I will award the points to you but do you know how I set the correction as an assisted solution. I dont want any of the points just to highlight the correction.
0
 
Daniel WilsonCommented:
On your comment, click Accept and Assign Points.  that will mark yours as the solution but permit you to mark mine as an assist.

Thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now