Convert binary string to decimal

I have a question about converting data from binary to decimal. Suppose I have a binary pattern like this:

pattern<-do.call(expand.grid, replicate(5, 0:1, simplify=FALSE))
pattern
   Var1 Var2 Var3 Var4 Var5
1     0    0    0    0    0
2     1    0    0    0    0
3     0    1    0    0    0
4     1    1    0    0    0
5     0    0    1    0    0
6     1    0    1    0    0
7     0    1    1    0    0
8     1    1    1    0    0
9     0    0    0    1    0
10    1    0    0    1    0
11    0    1    0    1    0
12    1    1    0    1    0
13    0    0    1    1    0
14    1    0    1    1    0
15    0    1    1    1    0
16    1    1    1    1    0
17    0    0    0    0    1
18    1    0    0    0    1
19    0    1    0    0    1
20    1    1    0    0    1
21    0    0    1    0    1
22    1    0    1    0    1
23    0    1    1    0    1
24    1    1    1    0    1
25    0    0    0    1    1
26    1    0    0    1    1
27    0    1    0    1    1
28    1    1    0    1    1
29    0    0    1    1    1
30    1    0    1    1    1
31    0    1    1    1    1
32    1    1    1    1    1

      

I am wondering in R what is the simplest way to convert each string to a decimal value? and against. eg:

00000->0
10000->16
...
01111->15

      

+3


source to share


2 answers


Try:

res <- strtoi(apply(pattern,1, paste, collapse=""), base=2)
res
#[1]  0 16  8 24  4 20 12 28  2 18 10 26  6 22 14 30  1 17  9 25  5 21 13 29  3
#[26] 19 11 27  7 23 15 31

      



You can try intToBits

converting back to binary

:

 pat2 <- t(sapply(res, function(x) as.integer(rev(intToBits(x)))))[,28:32]
 pat1 <- as.matrix(pattern)
 dimnames(pat1) <- NULL
identical(pat1, pat2)
#[1] TRUE

      

+6


source


You may try:



    as.matrix(pattern) %*% 2^((ncol(pattern)-1):0)

      

+4


source







All Articles