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

时间:2018-05-08 13:45:46

标签: postgresql ipv6

我有一个像byte \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.

1 个答案:

答案 0 :(得分:2)

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