PostgreSQL - Convert string to ASCII integer

Viewed 2388

How do I get the ASCII value of a string as an int in PostgreSQL?

For example: the string S06.6X9A

Currently, I am using an ASCII function, but it returns only the first character of a given string.

2 Answers

Use string_to_array('S06.6X9A', null) to split the string into a text[] of individual characters. Then unnest to turn that text[] into a table. Then use that in a from clause and run ascii() over each row.

select ascii(char)
from (
  select unnest( string_to_array('S06.6X9A', null) )
) as chars(char);

 ascii 
-------
    83
    48
    54
    46
    54
    88
    57
    65

Simpler than Schwern's answer is:

SELECT ascii( unnest( string_to_array('S06.6X9A', NULL) ) )
Related