How to get a hash code as integer in R?

我们两清 提交于 2019-12-06 03:17:25

问题


What I want to do is implement a hash trick in R.

Code below:

library(digest)
a<-digest("key_a", algo='xxhash32')
#[1] "4da5b0f8"

This returned a hash code in a character type. Is there any way I can turn it into a integer? Or is there any other package to achieve this?


回答1:


That output is a hex (base 16) string. Use following function to change it to decimal. Taken from another forum post but link does not work anymore (2017).

hex_to_int = function(h) {
  xx = strsplit(tolower(h), "")[[1L]]
  pos = match(xx, c(0L:9L, letters[1L:6L]))
  sum((pos - 1L) * 16^(rev(seq_along(xx) - 1)))
}

Output

> hex_to_int(a)
[1] 1302704376

But better answer is strtoi: as @Andrie said and @Gedrox answered, base::strtoi function works in the same way.

strtoi("4da5b0f8", 16)
[1] 1302704376



回答2:


There is a built in function base::strtoi:

> strtoi("4da5b0f8", 16)
[1] 1302704376


来源:https://stackoverflow.com/questions/27442991/how-to-get-a-hash-code-as-integer-in-r

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