【问题标题】:How to convert integer number into binary vector?如何将整数转换为二进制向量?
【发布时间】:2012-08-18 18:13:36
【问题描述】:

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

例如:

number <- 11
[1] 1 0 1 1

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

跟随兔子: base::intToBits

【问题讨论】:

    标签: r binary integer numeric binary-data


    【解决方案1】:

    intToBits 函数可以将任何整数转换为 32 个原始向量,因此您可以这样做:

    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
    

    【讨论】:

    • 第三行不应该是 1011 吗?
    • @nikpod 你想要第三列的反面,即0000...00001011
    • 我的错,正在逐行查看。数字 5 和 4 也巧合地以行表示
    • sapply(decimals,function(x)as.integer(paste(rev( as.integer(intToBits(x))),collapse="")))
    • @Onyambu:问题是关于将 int 转换为位矩阵;我的只是一个例子,当然你可以粘贴、子串、反转和对这些值进行任何你喜欢的操作。 :)
    【解决方案2】:

    这个SO post 建议使用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
    

    【讨论】:

    • 我收到length(number2binary(0, 32)) == 31...?
    【解决方案3】:

    试试 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
    

    还可用:移位、旋转、格雷码等。

    【讨论】:

      【解决方案4】:

      我在 M. J. Crawley 的“The R Book”中找到的解决方案是以下函数:

      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] 
      }
      

      【讨论】:

        【解决方案5】:

        您可以根据intToBit 使用以下函数:

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

        第一行将 intToBits 输出转换为数字 0 和 1,并直接排列顺序。第二行检查哪些值需要保留,如下:

        • 使用match 检查第一个 1 出现的位置。如果找不到 1,请让 match 返回您的 tmp 向量的长度。
        • 创建一个序列(使用seq_len),从1 到1tmp 向量中第一次出现之前的位置
        • 删除tmp 向量中的所有这些位置

        为了证明它有效:

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

        【讨论】:

          【解决方案6】:

          还有一个:

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

          【讨论】:

            【解决方案7】:

            如果你想返回一个二进制序列,即一个 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)
            }
            

            【讨论】:

              【解决方案8】:

              你实际上不需要调用任何函数来得到这个 - 单独的模运算可以给出答案。

              int_to_binary <- function(num, pow) {
                if(2^(pow + 1) - 1 < num) stop("Use a higher values of 'pow'")
                num %/% (2^(pow:0)) %% 2
              }
              

              【讨论】:

                【解决方案9】:
                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"
                

                如果你想要字符串而不是向量

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

                【讨论】:

                  【解决方案10】:

                  这是一个 Rcpp 实现。

                  在 Rstudio 中,将以下代码保存在文件中,例如 binary.cpp,然后键入 Source

                  //************************
                  // binary.cpp 
                  #include <RcppArmadillo.h>
                  
                  //' @Title get the binary representation of a positive integer
                  // [[Rcpp::depends(RcppArmadillo)]]
                  //[[Rcpp::export]]
                  void intToBinary(int n, arma::vec& a ) {
                    for(int i=0;n>0;i++){
                      a[i]=n%2;
                      n=n/2;
                    }
                  }
                  //************************
                  

                  如果 Source 顺利,来自 R 控制台类型

                  > a <- rep(0,10) # needed to store the binary representation
                  > myInt <- 5 # to be converted to binary form
                  > intToBinary(myInt, a)
                  > rev(a) # print in the usual form
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 2013-09-27
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2017-01-31
                    • 2011-08-10
                    • 2019-05-02
                    • 1970-01-01
                    相关资源
                    最近更新 更多