Presto - hex string to int

青春壹個敷衍的年華 提交于 2020-03-01 18:30:08

问题


I'm trying to convert hex string (starts with '0x') to it's integer value using presto. For example 0x100 to 256. My hex string is called msg_id. I tried to use this-

from_hex(substr(msg_id,3))

But I run into a problem, because from_hex expect even number of hex digits (0100 instead of 100). I decided to try and solve this using an if statement, so I tried this:

if(length(msg_id)%2=0, from_hex(substr(msg_id,3))) 

(will take care of the odd number of digits case later)

But- the result of from_hex is a varbinary type, with a varied number of bytes. I want to convert it to an Integer, or any other numeric type, but I can't find a way to do it.

Any ideas? I would appreciate it...


回答1:


You can use from_base(string, radix) to parse number written with hex digits into a bigint. You just need to strip leading '0x' first:

select from_base(substr('0x100', 3), 16);
 _col0
-------
   256

or with regexp_replace():

presto:tiny> select from_base(regexp_replace('0x100', '^0x'), 16);
 _col0
-------
   256


来源:https://stackoverflow.com/questions/50490705/presto-hex-string-to-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!