Postgres 9.4: fast way to convert color from hex to rgb

I have a hexadecimal view color, for a sample #112233

stored in Postgresql 9.4

You need to convert this view to rgb(17,34,51)

pl / pgsql functions

Any ideas for converting it quickly?

+3


source to share


1 answer


This uses the Erwin trick to convert a hex value to an integer value:

with colors (hex_code) as (
  values ('#112233'), ('#203040')
)
select 'rgb('||
       ('x'||substr(hex_code,2,2))::bit(8)::int||','||
       ('x'||substr(hex_code,4,2))::bit(8)::int||','||
       ('x'||substr(hex_code,6,2))::bit(8)::int||')'
from colors
;

      



Not sure if this is the fastest way, but I can't think of another. The expression select

can be moved into a function without issue.

SQLFiddle Demo: http://sqlfiddle.com/#!15/d41d8/3720

+5


source







All Articles