Re: bit operations

From: "Richard Huxton" <dev(at)archonet(dot)com>
To: Johan Björk <johan(at)websidorna(dot)com>, <pgsql-general(at)postgresql(dot)org>
Subject: Re: bit operations
Date: 2001-07-04 13:56:06
Message-ID: 003f01c10491$14201360$1001a8c0@archonet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

From: "Johan Björk" <johan(at)websidorna(dot)com>

> Have a little problem with bit operaitions that I cannot find the answer
to on the Internet. Have been searching through the archives but no result.
>
> In MySQL you can have a INT column and do bit logic ala C-style like this:
> "select * from table where flags & 4;"

If you're using an int for "flags":

select * from table where (flags & 4) > 0;

The bitwise AND returns an integer rather than a boolean, and AFAIK SQL
doesn't follow C's rules on this.

> Can I do something similar with std SQL? I've been trying to cast
everything to BIT but without success, and I've also been creating a "flags
bit(4)", setting a row to "1000" (8) and trying to compare, but I have
absolutely no idea how to.
>
> Say I wanna check if 8 (1xxx) and 2 (xx1x) is set, how do I do that?!

To check two values just do:

SELECT * FROM table WHERE (flags & val1 & val2) > 0;

If you want to use BIT types you'll need something like:

SELECT * FROM table WHERE (flags & '0010100'::BIT) <> '0'::BIT;

and updates like

UPDATE table SET flags = flags | '0001000'::BIT;

Note the need to have the same string-length when using AND/OR.

HTH

- Richard Huxton

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Scott Holmes 2001-07-04 14:40:41 Re: lo wrappers - still working on it
Previous Message Fariba Noorbakhsh 2001-07-04 13:53:39 Table Description!!