Last active
August 31, 2017 07:17
-
-
Save lujiajing1126/f9c7e2e63e50f2672b20609d0823215d to your computer and use it in GitHub Desktop.
PG Cast Helpers
This file contains 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 bit2text(BIT VARYING) | |
RETURNS TEXT | |
AS $$ | |
SELECT textin(bit_out($1)); | |
$$ LANGUAGE 'sql'; |
This file contains 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 bit_count(bitVal BIT VARYING) | |
RETURNS INTEGER AS $$ | |
BEGIN | |
RETURN LENGTH( REPLACE( CAST( bitVal AS TEXT ), '0','')); | |
END; | |
$$ LANGUAGE 'plpgsql' IMMUTABLE STRICT; |
This file contains 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 hex_to_bit(hexVal VARCHAR) | |
RETURNS BIT VARYING AS $$ | |
DECLARE | |
bitResult BIT VARYING := 0; | |
hexLength INTEGER; | |
i INTEGER; | |
hexDigit VARCHAR; | |
BEGIN | |
hexLength := length(hexVal); | |
FOR i IN 1..hexLength | |
LOOP | |
hexDigit := substr(hexVal, hexLength - i + 1, 1); | |
IF i = 1 | |
THEN | |
bitResult := B'000' || bitResult; | |
ELSE | |
bitResult := B'0000' || bitResult; | |
END IF; | |
bitResult := bitResult | | |
text2bitstring(rpad(bit2text((('X' || hexDigit) :: BIT(4))), i * 4, '0')); | |
END LOOP; | |
RETURN bitResult; | |
END; | |
$$ | |
LANGUAGE 'plpgsql' IMMUTABLE STRICT; |
This file contains 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 text2bitstring(TEXT) | |
RETURNS BIT VARYING | |
AS $$ | |
SELECT bit_in(textout('B' :: TEXT || $1), 67, length($1)); | |
$$ LANGUAGE 'sql'; | |
COMMENT ON FUNCTION text2bitstring(TEXT) IS 'Convert text (contianing 1''s and 0''s only) to a bit varying type.'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment