snippetsqlMajor
How do I write a hex literal in PostgreSQL?
Viewed 0 times
postgresqlliteralwritehexhow
Problem
How do you write a hex literal in PostgreSQL? Like say I want
So PostgreSQL is parsing the
0xCC, if I do;SELECT 0xCC;
xcc
-----
0
(1 row)So PostgreSQL is parsing the
xcc as an alias.Solution
Arbitrary Data / Integers (
You can write the hexidemical byte using Bit-string constants
Which is essentially the same as
UTF-8 Byte Sequence
If the byte sequences is a valid UTF-8 character, you can also use
If the sequence is invalid, you'll get an error
PostgreSQL has a variable-length binary data type that allows arbitrary bytes. This type is called
Here are both syntax,
Storing large numbers
If you only need to store large numbers, rather than storing them as
int)You can write the hexidemical byte using Bit-string constants
SELECT x'CC'; -- same as b'11001100'Which is essentially the same as
bit x'CC' returning a Bit String Type but there is a cast available to int so you can do x'CC'::int * 5UTF-8 Byte Sequence
If the byte sequences is a valid UTF-8 character, you can also use
E'' with a backslash-escape sequence (single backslash \)SELECT E'\x41';
?column?
----------
A
(1 row)If the sequence is invalid, you'll get an error
# SELECT E'\xCC';
ERROR: invalid byte sequence for encoding "UTF8": 0xccbytea-specific.PostgreSQL has a variable-length binary data type that allows arbitrary bytes. This type is called
bytea. You can move into this format using the bytea hex format. In this we either use,- Use a double backslash
\\
- Use the cast to
byteafrom from the hex representation.
Here are both syntax,
SELECT bytea E'\\xDEADBEEF', bytea '\xDEADBEEF';
bytea | bytea
------------+------------
\xdeadbeef | \xdeadbeef
(1 row)Storing large numbers
If you only need to store large numbers, rather than storing them as
bytea I would check out pg_bignum which stores them using the openssl implementation of Big Numbers.Code Snippets
SELECT x'CC'; -- same as b'11001100'SELECT E'\x41';
?column?
----------
A
(1 row)# SELECT E'\xCC';
ERROR: invalid byte sequence for encoding "UTF8": 0xccSELECT bytea E'\\xDEADBEEF', bytea '\xDEADBEEF';
bytea | bytea
------------+------------
\xdeadbeef | \xdeadbeef
(1 row)Context
StackExchange Database Administrators Q#203358, answer score: 23
Revisions (0)
No revisions yet.