2012-08-23 28 views
16

Cómo convertir un número entero en vector binario usando R?Cómo convertir un número entero en un vector binario?

Por ejemplo:

number <- 11 
[1] 1 0 1 1 

lo que es el método más rápido posible de la conversión (utilizando el código de R o algunas de las funciones existentes de paquetes) si necesita para convertir vector conjunto de números (valor mínimo = 0, máximo = 300) en matriz binaria?

Respuesta

19

está la función intToBits que convierte cualquier número entero a un vector de 32 azúcar sin refinar, por lo que se puede hacer esto:

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 
+0

¿no debería la 3ª fila ser 1011? – nikpod

+0

@nikpod Usted quiere el reverso de la tercera columna, que es '0000 ... 00001011' – digEmAll

+0

mi mal, lo estaba mirando en fila. Los números 5 y 4 están casualmente representados en filas también – nikpod

17

Este SO post sugiere la función intToBits. Defino la función number2binary, que incluye un argumento noBits para controlar cuántos bits se devuelven. Estándar es devolver 32 bits.

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

Y para algunos ejemplos:

> 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 
+0

obtengo 'longitud (number2binary (0, 32)) == 31' ...? –

5

usted podría utilizar la siguiente función para eso, basado en intToBit:

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

La primera línea convierte la salida intToBits en un 0 y 1 numérico, y ordena el orden. La segunda línea verifica qué valores deben retenerse, de la siguiente manera:

  • ver dónde se produce el primer 1 usando match. Si no puede encontrar 1, solicite match para devolver la longitud de su vector tmp.
  • crear una secuencia (utilizando seq_len) desde 1 a la posición anterior a la primera aparición de 1 en el vector tmp
  • caer todas aquellas posiciones en el vector tmp

Para mostrar funciona:

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

Una solución que he encontrado en "The R Book" por MJ Crawley es la siguiente función:

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

¡Esta función es genial! Es, de lejos, la solución más general. ¡Felicitaciones! –

2

Si desea devolver una secuencia binaria, es decir, un vector de 1 y 0, esta función lo hará por usted, pero solo puede tomar 1 número a la vez.

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) 
} 
1

Y otro:

toBits <- function (x, nBits = 8){ 
    tail(rev(as.numeric(intToBits(x))),nBits) 
} 
0
intToBin <- function(x){ 
    if (x == 1) 
    1 
    else if (x == 0) 
    NULL 
    else { 
    mod <- x %% 2 
    c(intToBin((x-mod) %/% 2), mod) 
    } 
} 

Así intToBin (10) devuelve

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

Y si quieres cadena en lugar de vectores

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

Prueba el paquete 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 

También disponible: desplazamiento, rotación, etc. graycode

Cuestiones relacionadas