代码之家  ›  专栏  ›  技术社区  ›  Aadith Ramia

R-如何将整数转换为位向量[[副本]

r
  •  1
  • Aadith Ramia  · 技术社区  · 6 年前

    "0000000000000101" )在R?有 intToBits

    > intToBits(12)
     [1] 00 00 01 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    [26] 00 00 00 00 00 00 00
    

    我尝试了一些其他功能,但没有成功:

    > toString(intToBits(12))
    [1] "00, 00, 01, 01, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00"
    
    0 回复  |  直到 12 年前
        1
  •  24
  •   Joshua Ulrich    6 年前

    注意 intToBits() @nico's original answer 从每个位删除前导“0”:

    paste(sapply(strsplit(paste(rev(intToBits(12))),""),`[[`,2),collapse="")
    [1] "00000000000000000000000000001100"
    

    # bit pattern for the 32-bit integer '12'
    x <- intToBits(12)
    # reverse so smallest bit is first (little endian)
    x <- rev(x)
    # convert to character
    x <- as.character(x)
    # Extract only the second element (remove leading "0" from each bit)
    x <- sapply(strsplit(x, "", fixed = TRUE), `[`, 2)
    # Concatenate all bits into one string
    x <- paste(x, collapse = "")
    x
    # [1] "00000000000000000000000000001100"
    

    @nico showed ,我们可以使用 as.integer()

    x <- rev(intToBits(12))
    x <- paste(as.integer(x), collapse = "")
    # [1] "00000000000000000000000000001100"
    

    为方便复制粘贴,以下是上述功能的一个功能版本:

    dec2bin <- function(x) paste(as.integer(rev(intToBits(x))), collapse = "")
    
        2
  •  27
  •   nico    13 年前

    paste(rev(as.integer(intToBits(12))), collapse="") 做这项工作

    paste collapse 参数将向量折叠为字符串。你必须使用 rev 但要获得正确的字节顺序。

    as.integer

        3
  •  19
  •   BenMorel Manish Pradhan    10 年前

    我认为可以使用R.utils包,然后使用intToBin()函数

    >library(R.utils)
    
    >intToBin(12)
    [1] "1100"
    
    > typeof(intToBin(12))
    [1] "character"
    
        4
  •  12
  •   inscaven    9 年前

    intToBits numeric .

    dec2bin <- function(fnum) {
      bin_vect <- rep(0, 1 + floor(log(fnum, 2)))
      while (fnum >= 2) {
        pow <- floor(log(fnum, 2))
        bin_vect[1 + pow] <- 1
        fnum <- fnum - 2^pow
      } # while
      bin_vect[1] <- fnum %% 2
      paste(rev(bin_vect), collapse = "")
    } #dec2bin
    

    microbenchmark(dec2bin(1e10+111))
    # Unit: microseconds
    #                 expr     min       lq     mean   median      uq    max neval
    # dec2bin(1e+10 + 111) 123.417 125.2335 129.0902 126.0415 126.893 285.64   100
    dec2bin(9e15)
    # [1] "11111111110010111001111001010111110101000000000000000"
    dec2bin(9e15 + 1)
    # [1] "11111111110010111001111001010111110101000000000000001"
    dec2bin(9.1e15 + 1)
    # [1] "100000010101000110011011011011011101001100000000000000"
    
        5
  •  6
  •   Chris    13 年前

    看看R.utils包-这里有一个名为intToBin的函数。。。

    http://rss.acs.unt.edu/Rdoc/library/R.utils/html/intToBin.html

        6
  •  5
  •   petew    10 年前

    此函数将获取一个十进制数并返回相应的二进制序列,即1和0的向量

    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)
    }
    
        7
  •  5
  •   Barranka Avinash Babu    9 年前

    bit64

    o.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)
    }
    
    dat <- sort(sample(0:.Machine$integer.max,1000000))
    system.time({sapply(dat,o.dectobin)})
    #   user  system elapsed 
    # 61.255   0.076  61.256 
    

    我们可以把它编译得更好。。。

    library(compiler)
    c.dectobin <- cmpfun(o.dectobin)
    system.time({sapply(dat,c.dectobin)})
    #   user  system elapsed 
    # 38.260   0.010  38.222 
    

    ... 但它仍然相当缓慢。如果我们用C编写自己的内部代码(这是我在这里借用@epwalsh的代码所做的事情——显然,我不是C程序员),我们可以大大加快速度。。。

    library(Rcpp)
    library(inline)
    library(compiler)
    intToBin64.worker <- cxxfunction( signature(x = "string") , '    
    #include <string>
    #include <iostream>
    #include <sstream>
    #include <algorithm>
    // Convert the string to an integer
    std::stringstream ssin(as<std::string>(x));
    long y;
    ssin >> y;
    
    // Prep output string
    std::stringstream ssout;
    
    
    // Do some math
    int64_t q2;
    int64_t q1 = (y / 2) / 1;
    int64_t r = y - q1 * 2;
    ssout << r;
    while (q1 >= 1) {
    q2 = (q1 / 2) / 1;
    r = q1 - q2 * 2;
    q1 = q2;
    ssout << r;
    }
    
    
    // Finalize string
    //ssout << r;
    //ssout << q1;
    std::string str = ssout.str();
    std::reverse(str.begin(), str.end());
    return wrap(str);
    ', plugin = "Rcpp" )
    
    system.time(sapply(as.character(dat),intToBin64.worker))
    #   user  system elapsed 
    #  7.166   0.010   7.168 
    

    ```

        8
  •  2
  •   lemon    8 年前

    试试二进制逻辑

    library(binaryLogic)
    
    ultimate_question_of_life_the_universe_and_everything <- as.binary(42)
    
    summary(ultimate_question_of_life_the_universe_and_everything)
    #>   Signedness  Endianess value<0 Size[bit] Base10
    #> 1   unsigned Big-Endian   FALSE         6     42
    
    > as.binary(0:3, n=2)
    [[1]]
    [1] 0 0
    
    [[2]]
    [1] 0 1
    
    [[3]]
    [1] 1 0
    
    [[4]]
    [1] 1 1
    
        9
  •  1
  •   MichaelChirico    5 年前

    --最初作为编辑添加到@JoshuaUlrich的答案中,因为这完全是他和@nico的推论;他建议我添加一个单独的答案,因为它在他的知识之外引入了一个包--

    因为@JoshuaUlrich的答案非常实用(6个背对背的函数),我找到了管道( %>% )操作员 magrittr / tidyverse 使以下解决方案更加优雅:

    library(magrittr)
    
    intToBits(12) %>% rev %>% as.integer %>% paste(collapse = '')
    # [1] "00000000000000000000000000001100"
    

    as.integer 调用以截断所有前导零:

    intToBits(12) %>% rev %>% as.integer %>% paste(collapse = '') %>% as.integer
    # [1] 1100
    

    integer ,表示R将其视为以10为基数表示的1100,而不是以2为基数表示的12)

    注意,@ RAMANUDLE(和其他人,特别是@ RaselsPurCE,给出C++实现)的方法通常是低级语言中提出的标准,因为它是一种非常有效的方法(并且它适用于任何可以存储在R中的数字,即,不限于 整数 射程)。

    还值得一提的是 C implementation of intToBits https://en.wikipedia.org/wiki/Bitwise_operations_in_C 对于仅限R用户可能不熟悉的零件

        10
  •  -2
  •   Kenzo_Gilead    7 年前
    decimal.number<-5
    
    i=0
    
    result<-numeric()
    
    while(decimal.number>0){
    
      remainder<-decimal.number%%2
    
      result[i]<-remainder
    
      decimal.number<-decimal.number%/%2
    
      i<-i+1
    }