albay_aureliano
albay_aureliano

Reputation: 407

Convert hex to decimal in R

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?

Upvotes: 33

Views: 32184

Answers (5)

Fato39
Fato39

Reputation: 890

As mentioned in @user4221472's answer, strtoi() overflows with integers larger than 2^31.

The simplest way around that is to use as.numeric().

V <- c(0xa373, 0x115c6, 0x176b3, 0x25cf40000)

as.numeric(V)
#[1]       41843       71110       95923 10149429248

As @MS Berends noted in the comments, "[a]lso notice that just printing V in the console will already print in decimal."

Upvotes: 15

Jean Castro
Jean Castro

Reputation: 331

To get a signed value with 16 bits:

  temp <- strtoi(value, base=16L)
  if (temp>32767){ temp <- -(65535 - temp) }

In a general form:

  max_unsigned <- 65535 #0xFFFF
  max_signed <- 32767 #0x7FFF
  temp <- strtoi(value, base=16L)
  if (temp>max_signed){ temp <- -(max_unsigned- temp) }

Upvotes: 0

user4221472
user4221472

Reputation: 81

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

Upvotes: 8

Vin&#237;cius Zambaldi
Vin&#237;cius Zambaldi

Reputation: 151

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"

Upvotes: 15

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 60000

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

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

Upvotes: 47

Related Questions