在postgresql中以ipv6格式转换十六进制字符串

converting hex string in ipv6 format in postgresql

我有一个 bytea 格式的十六进制字符串,如 \xfc80000000000000ea508bfff217b628,我想在 select 查询中将其转换为 fc80:0000:0000:0000:ea50:8bff:f217:b628,我试过:

select '0:0:0:0:0:0:0:0'::inet + encode(ip::bytea,'hex') from a;

但出现以下错误

ERROR:  operator does not exist: inet + text
LINE 1: select '0:0:0:0:0:0:0:0'::inet + encode(stationipv6::bytea,'...
                                       ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

substring()bytea 值一起使用,您可以使用它来提取字节的各个部分以将其转换为 inet

select concat_ws(':', 
                 encode(substring(stationipv6,  1, 2), 'hex'), 
                 encode(substring(stationipv6,  3, 2), 'hex'), 
                 encode(substring(stationipv6,  5, 2), 'hex'), 
                 encode(substring(stationipv6,  7, 2), 'hex'),
                 encode(substring(stationipv6,  9, 2), 'hex'), 
                 encode(substring(stationipv6, 11, 2), 'hex'), 
                 encode(substring(stationipv6, 13, 2), 'hex'), 
                 encode(substring(stationipv6, 15, 2), 'hex')
                 )::inet
from your_table

适用于 bytea