Convert hex to decimal in R

匿名 (未验证) 提交于 2019-12-03 08:33:39

问题:

I found out that there is function called .hex.to.dec in the fBasics package.

When I do .hex.to.dec(a), it works.

I have a data frame with a column samp_column consisting of such values:

a373, 115c6, a373, 115c6, 176b3 

When I do .hex.to.dec(samp_column), I get this error:

"Error in nchar(b) : 'nchar()' requires a character vector"

When I do .hex.to.dec(as.character(samp_column)), I get this error:

"Error in rep(base.out, 1 + ceiling(log(max(number), base = base.out))) : invalid 'times' argument"

What would be the best way of doing this?

回答1:

Use base::strtoi to convert hexadecimal character vectors to integer:

strtoi(c("0xff", "077", "123")) #[1] 255  63 123 


回答2:

There is a simple and generic way to convert hex <-> other formats using "C/C++ way":

V <- c(0xa373, 0x115c6, 0xa373, 0x115c6, 0x176b3)  sprintf("%d", V) #[1] "41843" "71110" "41843" "71110" "95923"  sprintf("%.2f", V) #[1] "41843.00" "71110.00" "41843.00" "71110.00" "95923.00"  sprintf("%x", V) #[1] "a373"  "115c6" "a373"  "115c6" "176b3" 


回答3:

strtoi() has a limitation of 31 bits. Hex numbers with the high order bit set return NA:

> strtoi('0x7f8cff8b') [1] 2139946891 > strtoi('0x8f8cff8b') [1] NA 


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