首页 > 解决方案 > 在 postgresql 中以 ipv6 格式转换十六进制字符串

问题描述

我有一个像\xfc80000000000000ea508bfff217b628bytea 格式的十六进制字符串,我想在选择查询中将其转换为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.

标签: postgresqlipv6

解决方案


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列上工作


推荐阅读