r - 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.
解决方案
如果您假设高位表示负数,那么
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
推荐阅读
- java - 为什么 ThreadMXBean.getThreadCpuTime 返回相同的时间?
- css - Bootstrap 响应式照片网格
- javascript - 从选项列表中过滤一些前缀
- c# - System.Windows.Forms.Timer 和 C# 的垃圾收集
- facebook - 是否可以与我的个人 Facebook 墙进行交互并通过 API 提供信息?
- android - Android 开发人员可以在用户启动应用程序之前运行代码吗?
- android - 如何在 init 中运行服务(Android 8.1)
- gitlab - 合并失败:合并请求不可合并。请再试一次
- linux-device-driver - 如何查看设备驱动源文件
- java - 如何在我的主要活动中声明一个新的 Java 类?