Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hex to decimal in R

Tags:

r

decimal

hex

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?

like image 752
albay_aureliano Avatar asked Oct 21 '13 18:10

albay_aureliano


People also ask

How to read hexadecimal numbers?

Hex numbers are read the same way, but each digit counts power of 16 instead of power of 10. For hex number with n digits: d n-1 ... Multiply each digit of the hex number with its corresponding power of 16 and sum: decimal = d n-1×16 n-1 + ...

How do you convert hex to decimal?

Hex to decimal conversion table Hex base 16 Decimal base 10 Calculation 90 144 9×16 1 +0×16 0 = 144 A0 160 10×16 1 +0×16 0 = 160 B0 176 11×16 1 +0×16 0 = 176 C0 192 12×16 1 +0×16 0 = 192 46 more rows ...

How to format decimal places of one specific number in R?

If we want to format the decimal places of one specific number (or a vector of numbers), we can use the format function in combination with the round function and the specification nsmall. Consider the following R syntax: format ( round ( x, 3), nsmall = 3) # Apply format function # "10.766".

How to read a hex number with n digits?

Hex numbers are read the same way, but each digit counts power of 16 instead of power of 10. For hex number with n digits: d n-1 ... d 3 d 2 d 1 d 0. Multiply each digit of the hex number with its corresponding power of 16 and sum: decimal = d n-1×16 n-1 + ... + d 3×16 3 + d 2×16 2 + d 1×16 1+d 0×16 0.


2 Answers

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

strtoi(c("0xff", "077", "123")) #[1] 255  63 123 
like image 160
Simon O'Hanlon Avatar answered Sep 26 '22 03:09

Simon O'Hanlon


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" 
like image 20
Vinícius Zambaldi Avatar answered Sep 24 '22 03:09

Vinícius Zambaldi