本文分享自華為云社區《GaussDB(DWS)字串、二進制、十六進制互轉》,作者:你是猴子請來的救兵嗎 ,
概述
現網中遇到很多小伙伴不清楚字串與進制之間的轉換方法,其實在GaussDB(DWS)中,進制轉換是非常方便的,這次就來對不同的場景一一進行決議,整理出來供大家翻閱參考,
字串&二進制 互轉
# 字串轉二進制,使用型別轉換 select bytea('華為'::text); select '華為'::text::bytea; select cast('華為'::text as bytea); bytea ---------------- \xe58d8ee4b8ba (1 row) # 二進制轉字串,使用convert_from,第二個引數為編碼 select convert_from('\xe58d8ee4b8ba'::bytea,'utf8'); convert_from -------------- 華為 (1 row)
二進制&十六進制 互轉
# 二進制轉十六進制,可以使用encode, select encode('\xe58d8ee4b8ba'::bytea,'hex'); hex -------------- e58d8ee4b8ba (1 row) # 十六進制轉二進制,820版本可以使用unhex,低于820版本可以使用decode select unhex('e58d8ee4b8ba'::text); unhex ---------------- \xe58d8ee4b8ba (1 row) select decode('e58d8ee4b8ba'::text,'hex'); decode ---------------- \xe58d8ee4b8ba (1 row)
字串&十六進制 互轉
# 字串轉十六進制,820版本可以使用hex,低于820版本可以使用encode select hex('華為'::text); hex -------------- E58D8EE4B8BA (1 row) select encode('華為'::text::bytea, 'hex'); encode -------------- e58d8ee4b8ba (1 row) # 十六進制轉字串,需先將十六進制轉換為二進制,再轉為字串 select convert_from(unhex('E58D8EE4B8BA'),'utf8'); convert_from -------------- 華為 (1 row)
注意事項:
1,hex/unhex是820版本新增的一組十六進制的編碼/解碼函式,低于820版本需使用encode/decode函式替代,
hex行為與mysql資料庫保持一致,輸出全大寫的十六進制字串;encode輸出的是全小寫的十六進制字串;對大小寫有要求的小伙伴可以選擇滿足要求的函式,但實際在決議時是沒有影響的,
select hex('華為'::text); hex -------------- E58D8EE4B8BA (1 row) select encode('華為'::text::bytea, 'hex'); encode -------------- e58d8ee4b8ba (1 row)
2,在將二進制轉為字串的時候使用convert_from,第二個引數為源資料編碼,
需要注意的是,一定保證源資料編碼正確,否則就會產生非預期的結果,甚至報錯,
像這樣
# 源資料編碼為utf8,但決議時錯誤指定為gbk select convert_from(unhex('E58D8EE4B8BA'),'gbk'); convert_from -------------- 鍗庝負 (1 row)
這樣
# 源資料編碼為gbk,但決議時錯誤指定為utf8 select convert_from(unhex('bbaaceaa'),'utf8'); ERROR: invalid byte sequence for encoding "UTF8": 0xbb CONTEXT: referenced column: convert_from
知識小結
轉換函式encode
encode(data bytea, format text) 描述:將二進制資料編碼為文本資料, 回傳值型別:text SELECT encode('database', 'base64'); encode ---------- ZGF0YWJhc2U= (1 row) decode(string text, format text) 描述:將二進制資料從文本資料中解碼, 回傳值型別:bytea SELECT decode('ZGF0YWJhc2U=', 'base64'); decode -------------- \x6461746162617365 (1 row)
轉換函式convert_from
convert_from(string bytea, src_encoding name) 描述:以資料庫的編碼方式轉化字串bytea, src_encoding指定源編碼方式,在該編碼下,string必須是合法的, 回傳值型別:text SELECT convert_from('\x6461746162617365','gbk'); convert_from -------------- database (1 row)
轉換函式hex/unhex,需820或以上版本
hex(n) 描述:n可以是int型別也可以是字串,回傳n的十六進制字串,若引數含有NULL值,回傳NULL, 回傳值型別:text SELECT hex('abc') as result; result -------- 616263 (1 row) unhex(n) 描述:執行hex(n)的反向操作,n可以是int型別也可以是字串,將引數中的每一對十六進制數字理解為一個數字,并將其轉化為該數字代表的字符,若引數含有NULL值,回傳NULL, 回傳值型別:bytea SELECT unhex('616263') as result; result ---------- \x616263 (1 row)
點擊關注,第一時間了解華為云新鮮技術~
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/539574.html
標籤:其他
上一篇:跨機房ES同步實戰
