Last active
February 2, 2017 09:40
-
-
Save seansawyer/92543bd9fba5f0281074 to your computer and use it in GitHub Desktop.
PL/pgSQL function to convert a hexadecimal string to a bit varying
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
DROP FUNCTION IF EXISTS hex_to_bit_varying(hex_string text); | |
CREATE FUNCTION hex_to_bit_varying(hex_string text) RETURNS bit varying AS $$ | |
DECLARE | |
bytes bytea = decode(hex_string, 'hex'); | |
n int = length(bytes) * 8 - 1; | |
bits bit varying := B''::bit varying; | |
BEGIN | |
-- RAISE NOTICE 'bytes=%, n=%', bytes, n; | |
-- RAISE NOTICE 'bits=%', bits; | |
FOR i IN 0 .. n BY 8 LOOP | |
FOR j IN REVERSE 7 .. 0 LOOP | |
bits := bits || get_bit(bytes, i+j)::bit; | |
-- RAISE NOTICE 'offset=% (i=%, j=%), b=%, bits=%', i+j, i, j, get_bit(bytes, i+j), bits; | |
END LOOP; | |
END LOOP; | |
RETURN bits; | |
END; | |
$$ LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment