Created
May 29, 2020 22:34
-
-
Save MNoorFawi/275cc0a054212eade183515fb811acbf to your computer and use it in GitHub Desktop.
Implementing bit count function in PostgreSQL database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION bits_count(value bigint) RETURNS integer AS $$ | |
DECLARE i integer; | |
c integer; | |
bits BIT(25); | |
BEGIN | |
c := 0; | |
bits := value::BIT(25); | |
FOR i IN 1..LENGTH(bits) LOOP | |
IF substring(bits, i, 1) = B'1' THEN | |
c := c + 1; | |
END IF; | |
END LOOP; | |
RETURN c; | |
END; | |
$$ LANGUAGE plpgsql; | |
-- another one to accept only integer (coming from python calls mainly) | |
CREATE OR REPLACE FUNCTION bits_count(value integer) RETURNS integer AS $$ | |
DECLARE i integer; | |
c integer; | |
bits BIT(25); | |
BEGIN | |
c := 0; | |
bits := value::BIT(25); | |
FOR i IN 1..LENGTH(bits) LOOP | |
IF substring(bits, i, 1) = B'1' THEN | |
c := c + 1; | |
END IF; | |
END LOOP; | |
RETURN c; | |
END; | |
$$ LANGUAGE plpgsql; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
select bit_count(123::int::bit(32));
-- works as well with just the built-in functions