首页 > 解决方案 > How do I convert hex to numbers keeping the sign (+/-) in R?

问题描述

I am a first time poster so sorry if the format is not exactly as required.

I have a data frame that looks something like this, with each row containing three columns of hex strings:

   id   x
1  1   FFF8
2  2   FFBC
3  3   FFAE
4  4   0068

If I understand correctly, "FFF8" should convert to "-8", however all I have managed to do is convert it to the positive equivalent - "65528".

I have used:

dataframe$x<-as.numeric(dataframe$x)

I haven't found any R function that can maintain the minus sign, as intended.

Can anyone kindly help with converting the hex strings into a number whilst maintaining the intended minus sign?

Many thanks in advance.

标签: rhex

解决方案


如果您假设高位表示负数,那么

strtoi(dat$x, base=16)
# [1] 65528 65468 65454   104
dat$x2 <- strtoi(dat$x, base=16)
dat$x3 <- ifelse(bitwAnd(dat$x2, 0x8000) > 0, -0xFFFF-1, 0) + dat$x2
dat
#   id    x    x2  x3
# 1  1 FFF8 65528  -8
# 2  2 FFBC 65468 -68
# 3  3 FFAE 65454 -82
# 4  4 0068   104 104

推荐阅读