【问题标题】:Convert hexadecimal character vector to raw vector in R将十六进制字符向量转换为 R 中的原始向量
【发布时间】:2017-04-02 02:22:07
【问题描述】:

我正在尝试将下面显示的十六进制字符向量转换为原始向量,

"58" "0a" "00" "00" "00" "02" "00" "03" "02" "00" "00" "02" "03" "00" "00" "00" "03" "13" "00" "00"

我已经用这个代码试过了,

as.raw(hexvec)

但是,这给了我以下结果,

3a 00 00 00 00 02 00 03 02 00
Warning messages:
1: NAs introduced by coercion 
2: out-of-range values treated as 0 in coercion to raw

我想要的是原始类型向量中的相同向量(由序列化函数返回)。谁能帮我解决这个问题?

【问题讨论】:

    标签: r casting type-conversion


    【解决方案1】:

    您是否尝试过为向量中的每个元素应用函数charToRaw
    尝试使用此代码?

     sapply(hexvec,charToRaw)
    

    【讨论】:

      【解决方案2】:

      我想这有点晚了,但它可能会帮助其他人。

      hexchar_vector <- c("58", "0a", "00", "00", "00", "02", "00", "03", "02", "00", "00", "02", "03", "00", "00", "00", "03", "13", "00", "00")
      
      integer_vector <- base::strtoi(hexchar_vector, base = 16L) # Convert strings to integers according to the given base using the C function strtol, or choose a suitable base following the C rules.
      
      raw_vector <- base::as.raw(integer_vector) # Creates objects of type "raw" from integers.
      

      这给出了,有管道和没有命名空间引用:

      library(magrittr)
      hexchar_vector <- c("58", "0a", "00", "00", "00", "02", "00", "03", "02", "00", "00", "02", "03", "00", "00", "00", "03", "13", "00", "00")
      
      raw_vector  <- hexchar_vector %>%
        strtoi(16L) %>%
        as.raw()
      

      【讨论】:

        猜你喜欢
        • 2018-01-11
        • 2015-11-12
        • 2021-06-24
        • 1970-01-01
        • 2016-07-24
        • 2017-09-28
        • 1970-01-01
        • 2012-01-11
        • 2016-07-07
        相关资源
        最近更新 更多