簡體   English   中英

R / Rcpp:如何有效地將2字節的十六進制值轉換為整數?

[英]R/Rcpp: How can I convert 2-byte Hex values to integers efficiently?

我想將包含2個字節的十六進制數字(小尾數)的原始類型向量轉換為R中的整數向量(例如ff ff-> 0xffff = 65535)。 一種方法是從原始向量中提取偶數和奇數元素,然后粘貼到字符中,然后轉換為整數,如下所示:

> a <- c(as.raw(255), as.raw(254), as.raw(253), as.raw(252))
> a
[1] ff fe fd fc
> even_elem <- a[seq(2,length(a),2)]
> odd_elem <- a[seq(1,length(a),2)]
> as.integer(paste0("0x", even_elem, odd_elem))
[1] 65279 64765
> c(0xfeff, 0xfcfd)
[1] 65279 64765

問題是我想對具有> 10 ^ 8個元素的向量執行此操作。 如果我使用上述方法執行此操作,則需要幾分鍾。 我想要更高效的東西。 我以為可以嘗試使用Rcpp加快速度,所以我寫了一段cpp代碼(我是Rcpp / c ++的新手),

#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
IntegerVector raw2intC(CharacterVector vec){
  int n = vec.size();
  int m;
  Rcpp::IntegerVector x(n/2);
  for (int i = 0; i < n/2; i++) {
    std::string h1 = Rcpp::as<std::string>(vec[i*2]);
    std::string h2 = Rcpp::as<std::string>(vec[i*2 + 1]);
    h2 += h1;
    std::stringstream ss;
    ss << std::hex << h2;
    ss >> m;
    x[i] = m;
  }
return(x);
}

和一個R腳本。

raw2intR <- function(obj){
  val <- raw2intC(obj)
  val
}

該Rcpp代碼有效,並且微基准測試的結果令人鼓舞。

> microbenchmark(raw2intR(a), as.integer(paste0("0x", even_elem, odd_elem)))
Unit: microseconds
expr    min      lq     mean  median      uq     max
raw2intR(a)  4.953  5.9130  7.68194  7.4800  8.4585  42.658
as.integer(...) 36.297 40.4275 44.06539 42.8565 44.9420 147.110
> identical(raw2intR(a), as.integer(paste0("0x", even_elem, odd_elem)))
[1] TRUE

但是,當使用更大的向量進行測試時,R和Rcpp解決方案之間的執行時間並沒有太大差異。 實際上,R解決方案的速度稍快一些。

> b <- raw(1000000)
> even_elem <- b[seq(2,length(a),2)]
> odd_elem <- b[seq(1,length(a),2)]
> microbenchmark(raw2intR(b), as.integer(paste0("0x", even_elem, odd_elem)), times=10)
Unit: milliseconds
expr      min       lq     mean   median       uq
raw2intR(b) 309.4139 309.7920 316.6345 313.6219 321.5353
as.integer(...) 274.3523 279.6978 287.5415 288.1744 291.1616
> identical(raw2intR(b), as.integer(paste0("0x", even_elem, odd_elem)))
[1] TRUE

如何加快這項任務? 我希望實現10倍的改進。

謝謝你的建議。

無需構建字符串以轉換回數字,您只需告訴R直接使用readBin將這些原始值解釋為整數。 例如

a <- as.raw(c(255, 254, 253, 252))
readBin(a, "integer", n=length(a)/2, size=2, signed=FALSE)
# [1] 65279 64765

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM