Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert binary string to decimal

Tags:

r

I have a question on data conversion 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'm wondering in R what is the easiest way to convert each row to a decimal value? and versus. such as:

00000->0
10000->16
...
01111->15
like image 640
David Z Avatar asked Dec 19 '22 10:12

David Z


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 could try intToBits to convert back to the 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
like image 103
akrun Avatar answered Jan 06 '23 02:01

akrun


You can try:

    as.matrix(pattern) %*% 2^((ncol(pattern)-1):0)
like image 23
nicola Avatar answered Jan 06 '23 02:01

nicola