Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert binary vector to decimal

Tags:

r

decimal

binary

I have a vector of a binary string:

a<-c(0,0,0,1,0,1)

I would like to convert this vector into decimal.

I tried using the compositions package and the unbinary() function, however, this solution and also most others that I have found on this site require g-adic string as input argument.

My question is how can I convert a vector rather than a string to decimal?

to illustrate the problem:

library(compositions)
unbinary("000101") 
[1] 5

This gives the correct solution, but:

unbinary(a)
unbinary("a")
unbinary(toString(a)) 

produces NA.

like image 943
user1723765 Avatar asked Aug 20 '14 17:08

user1723765


2 Answers

You could try this function

bitsToInt<-function(x) {
    packBits(rev(c(rep(FALSE, 32-length(x)%%32), as.logical(x))), "integer")
}

a <- c(0,0,0,1,0,1)
bitsToInt(a)
# [1] 5

here we skip the character conversion. This only uses base functions.

It is likely that

 unbinary(paste(a, collapse=""))

would have worked should you still want to use that function.

like image 51
MrFlick Avatar answered Sep 17 '22 23:09

MrFlick


There is a one-liner solution:

Reduce(function(x,y) x*2+y, a)

Explanation:

Expanding the application of Reduce results in something like:

Reduce(function(x,y) x*2+y, c(0,1,0,1,0)) = (((0*2 + 1)*2 + 0)*2 + 1)*2 + 0 = 10

With each new bit coming next, we double the so far accumulated value and add afterwards the next bit to it.

Please also see the description of Reduce() function.

like image 38
Grisha Avatar answered Sep 21 '22 23:09

Grisha