2016-08-10 8 views
2

私はRで作業しています。最高の整数のビットをマスクする高速関数を見つける必要があります。例:Rのマスキング最高設定ビット?

これは、最も近い2の累乗を引くのと同じです。私は、2つの最も近い低電力を簡単に見つける高速な関数を見つけることができれば幸いです。例:

# 6 in binary is 110, the MSB is 100 
function_power_two(6) = 4 
function_mask(6) = 6 - function_power_two(6) = 2 

# 8 in binary is 1000, the MSB is 1000 which is 8 in base 10 
function_power_two(8) = 8 
function_mask(8) = 8 - function_power_two(8) = 0 

ビット単位の演算がRで見つかりました。たとえば、bitwShiftLとbitwShiftRです。しかし、私はRのソリューションを実装する方法を知りません

私は他の言語のソリューションを見てきました:JavaC、およびC++です。しかし、Rでこれらのソリューションを実装する方法はわかりません

Rcppを使用するC++のソリューションはありますが、Rcppは32ビットより大きい整数をサポートしていません。私はそれより大きな整数が必要です。 Rソリューションの

答えて

1

この関数は、 01よりもさらに高速(4倍)です。

pow2 <- c(0,1,2,4,8,16,32,64,128,256,512,1024) 
function_mask <- function(x) x - pow2[findInterval(x, pow2)] 

あなたはより大きな整数

に対処するために、限り、必要に応じてPOW2ベクトルを作ることができます
0

:他の回答に速度を比較すると

function_mask <- function(x) { 
    xb <-intToBits(x) 
    highestbit <- length(xb) - match("01", rev(xb)) 
    x-2L^highestbit 
} 

、私たちはこの1つは、これまで、最速でご覧ください。

function_mask1 <- function(x) { 
    bits = intToBits(x)     # Convert integer to binary vector 
    ii = tail(which(bits > 0), n=1)  # Identify most significant bit 
    bits[ii] = as.raw(0)    # Mask the most significant bit 
    out = packBits(bits,type='integer') # Convert binary back to integer 
    return(out) 
} 

maskHighBit <- function(x){ 
    strtoi(gsub("^1", "", R.utils::intToBin(as.integer(x))), base=2)} 

library(microbenchmark) 
microbenchmark(function_mask(112L), function_mask1(112L), maskHighBit(112L), times=1000) 
#Unit: microseconds 
#expr  min  lq  mean median  uq  max neval cld 
#function_mask(112L) 17.961 20.014 23.65080 23.092 24.632 57.475 1000 a 
#function_mask1(112L) 39.514 44.132 49.79744 47.724 49.777 107.765 1000 b 
#maskHighBit(112L) 108.791 114.435 127.53792 118.540 133.422 2054.189 1000 c 
1

あなたはこのような何か行うことができます:

function_mask <- function(x) { 
    bits = intToBits(x)     # Convert integer to binary vector 
    ii = tail(which(bits > 0), n=1)  # Identify most significant bit 
    bits[ii] = as.raw(0)    # Mask the most significant bit 
    out = packBits(bits,type='integer') # Convert binary back to integer 
    return(out) 
} 

テスト:それは速いかどう

function_mask(6) = 2 
function_mask(8) = 0 
1

わからないが、しかし、ここでもう一つの可能​​性だ:

maskHighBit <- function(x){strtoi(sub("^1", "", R.utils::intToBin(x)), base=2)} 
関連する問題