PostgreSQL 十六進位制轉為整數函式
PostgreSQL有整數轉為字串的函式to_hex,但卻沒有提供反過來的函式,因為要用到,寫了一個與大家分享。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
create or replace function hex_to_int(s character varying) returns bigint as $$ declare retval bigint; lead character varying; begin lead=left(s,1); if (lead='$') or (lead='h') or (lead='H') then lead=right(s,length(s)-1); else begin lead=left(s,2); if (lead='0x') or (lead='0X') then lead=right(s,length(s)-2); else raise exception end if; end; end if; s='x'||repeat('0',16-length(lead))||lead; --raise notice 'hexchars=%',s; retval=cast(cast(s as bit(64)) as bigint); return retval; end; $$ language plpgsql immutable strict; |
呼叫時,只需要簡單的將其賦值給一個變數,或者如select hex_to_int(‘0x0220’);這樣子呼叫一下就可以。
這個函式支援Delphi/C++/Basic的十六進位制表示方式。
1 2 3 |
select hex_to_int('0x0100'); select hex_to_int('$0100'); select hex_to_int('H0100'); |