我正在 R 中工作。我需要找到一个快速函数来屏蔽整数的最高设置位。例如:
# 6 binary is 110, this should turn into 010 which is 2
function_mask(6) = 2
# 8 in binary is 1000, this should turn into 0000
function_mask(8) = 0
这相当于减去最接近的较低的二的幂。如果我能找到一个快速函数来简单地找到最接近的较低的两个幂,我会很高兴。例如:
# 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 中实现解决方案。
我见过其他语言的解决方案:Java , C ,和 C++ 。但是,我不知道如何在 R 中实现这些解决方案。
C++ 中有使用 Rcpp 的解决方案,但 Rcpp 不支持大于 32 位的整数。我需要比这更大的整数。
最佳答案
此函数比 the answer I posted earlier 更快 (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 向量,以应对更大的整数
关于r - 屏蔽 R 中的最高设置位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38879212/