如何将整数转换为二进制向量?

如何使用R将整数转换为二进制向量?

例如 :

number <- 11 [1] 1 0 1 1 

如果我需要将整个数字向量(最小值= 0,最大值= 300)转换成二进制matrix,那么最快可能的转换方法是什么(使用R代码或包中的一些现有函数)?

intToBits函数可以将任何整数转换为32个intToBits的vector,所以你可以这样做:

 decimals <- c(3,5,11,4) m <- sapply(decimals,function(x){ as.integer(intToBits(x))}) m > m [,1] [,2] [,3] [,4] [1,] 1 1 1 0 [2,] 1 0 1 0 [3,] 0 1 0 1 [4,] 0 0 1 0 [5,] 0 0 0 0 [6,] 0 0 0 0 [7,] 0 0 0 0 [8,] 0 0 0 0 [9,] 0 0 0 0 [10,] 0 0 0 0 [11,] 0 0 0 0 [12,] 0 0 0 0 [13,] 0 0 0 0 [14,] 0 0 0 0 [15,] 0 0 0 0 [16,] 0 0 0 0 [17,] 0 0 0 0 [18,] 0 0 0 0 [19,] 0 0 0 0 [20,] 0 0 0 0 [21,] 0 0 0 0 [22,] 0 0 0 0 [23,] 0 0 0 0 [24,] 0 0 0 0 [25,] 0 0 0 0 [26,] 0 0 0 0 [27,] 0 0 0 0 [28,] 0 0 0 0 [29,] 0 0 0 0 [30,] 0 0 0 0 [31,] 0 0 0 0 [32,] 0 0 0 0 

这SOpostbuild议intToBits函数。 我定义了函数number2binary ,它包含一个参数noBits来控制返回的位数。 标准是返回32位。

 number2binary = function(number, noBits) { binary_vector = rev(as.numeric(intToBits(number))) if(missing(noBits)) { return(binary_vector) } else { binary_vector[-(1:(length(binary_vector) - noBits))] } } 

举一些例子:

 > number2binary(11) [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 > number2binary(11, 4) [1] 1 0 1 1 

我在MJ Crawley的“The R Book”中find的一个解决scheme是:

 binary <- function(x) { i <- 0 string <- numeric(32) while(x > 0) { string[32 - i] <- x %% 2 x <- x %/% 2 i <- i + 1 } first <- match(1, string) string[first:32] } 

你可以使用下面的函数,基于intToBit

 intToBitVect <- function(x){ tmp <- rev(as.numeric(intToBits(x))) id <- seq_len(match(1,tmp,length(tmp))-1) tmp[-id] } 

第一行将intToBits输出转换为数字0和1,并直接放置订单。 第二行检查哪些值需要保留,如下所示:

  • 使用match检查第一个出现在哪里。 如果找不到1,则请求match返回tmp向量的长度。
  • 创build一个序列(使用seq_len )从1到tmp向量中第一个出现1之前的位置
  • 将所有这些位置放在tmp向量中

展示它的作品:

 > intToBitVect(11) [1] 1 0 1 1 > intToBitVect(0) [1] 0 

如果你想返回一个二进制序列,即1和0的向量,那么这个函数将为你做,但它一次只能取1个数字。

 dectobin <- function(y) { # find the binary sequence corresponding to the decimal number 'y' stopifnot(length(y) == 1, mode(y) == 'numeric') q1 <- (y / 2) %/% 1 r <- y - q1 * 2 res = c(r) while (q1 >= 1) { q2 <- (q1 / 2) %/% 1 r <- q1 - q2 * 2 q1 <- q2 res = c(r, res) } return(res) } 

另一个:

 toBits <- function (x, nBits = 8){ tail(rev(as.numeric(intToBits(x))),nBits) } 

尝试CRAN包“binaryLogic”

 library(binaryLogic) as.binary(11) [1] 1 0 1 1 as.binary(11, littleEndian=TRUE) [1] 1 1 0 1 as.binary(42, n=16) [1] 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 as.binary(0:2, n=2) [[1]] [1] 0 0 [[2]] [1] 0 1 [[3]] [1] 1 0 as.binary(0xFF) [1] 1 1 1 1 1 1 1 1 

还有:移位,旋转,灰度等

 intToBin <- function(x){ if (x == 1) 1 else if (x == 0) NULL else { mod <- x %% 2 c(intToBin((x-mod) %/% 2), mod) } } 

所以intToBin(10)返回

 [1] "1" "0" "1" "0" 

如果你想要string而不是vector

 > paste0(intToBin(10), collapse = "") [1] "1010"