Convert hex string to bigint in Postgres [duplicate]

左心房为你撑大大i 提交于 2019-12-21 05:43:44

问题


I'd like to convert a hex string as used by HTML into a bigint to then convert it into separate R, G and B values in Postgres via a function written in PL/pgSQL.

I can decode the string into bytea like this:

hex bytea := decode(hex, 'hex');

And in a query with fixed values this works like a beauty:

select ( array[ (cast(x'ffaa33' as bigint) >> 16) % 256,
                (cast(x'ffaa33' as bigint) >> 8) % 256,
                 cast(x'ffaa33' as bigint) % 256 ] )

But I can't put the two together, passing - for example 'ffaa33' as parameter.

Anyone got a better idea? I'm using PosgreSQL 9.1?


回答1:


An easy way is:

 select ('x'||lpad(the_hex_value,16,'0'))::bit(64)::bigint;

The left padding with 0 is necessary because the leftmost bit is always going to be interpreted as the sign bit. Also keep in mind that bigint is signed, postgres doesn't have built-in unsigned types.



来源:https://stackoverflow.com/questions/12375369/convert-hex-string-to-bigint-in-postgres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!