Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

The goal is to fast extract bit at position N; So far i've found only this way to do that:

CREATE OR REPLACE FUNCTION test(x int, size int)
RETURNS int AS
$BODY$
DECLARE
y int;

BEGIN
    y = get_bit(x::bit(size)>>size-1,size-1);


    return y;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;

But this says because of bit(size)

invalid input syntax for integer: "size"

So i'm forsed to write size as a constant, for example bit(3)

Is there any way to set bit size dynamically? Alternatively, maybe there are some other ways to extract specific bit of int/text?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

You don't need bitfield types for this. To test bit 6 of the value 200:

SELECT 200 & (1<<6) != 0

you binary-AND a value with the 6th bit set, by upshifting 1 by 6 base-2 places, then test to see if the result is nonzero.

Alternately, cast to a suitable bit size based on the integer and use position, though I think there's no reason whatsoever to do that when you can use extremely fast bitwise AND and shifts like above. Because get_bit numbers from the left, and uses a 1-offset instead of 0-offset, you have to take the compliment of 31 (for a 32-bit int) to get the position from the right:

SELECT get_bit(200::bit(32), 31 - 6);

so it's way simpler to just use bitwise operations like the first example.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.