Skip to content

Instantly share code, notes, and snippets.

@seansawyer
Last active February 2, 2017 09:40
Show Gist options
  • Save seansawyer/92543bd9fba5f0281074 to your computer and use it in GitHub Desktop.
Save seansawyer/92543bd9fba5f0281074 to your computer and use it in GitHub Desktop.
PL/pgSQL function to convert a hexadecimal string to a bit varying
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