Convert binary to decimal

I have a binary string vector:

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

I would like to convert this vector to decimal.

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

My question is: how to convert a vector, not 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)) 

creates NA.

+6
source share
4 answers

You can try this feature.

 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 character conversion. This uses only base functions.

Probably,

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

would work if you still want to use this feature.

+7
source

There is a one line solution:

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

Explanation:

Extending a Reduce application leads to 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 following it, we double the previously accumulated value and add the next bit to it.

Also see the description of the Reduce() function.

+5
source

If you want to use compositions, just convert the vector to a string:

 library(compositions) a <- c(0,0,0,1,0,1) achar <- paste(a,collapse="") unbinary(achar) [1] 5 
+4
source

This function will do the trick.

 bintodec <- function(y) { # find the decimal number corresponding to binary sequence 'y' if (! (all(y %in% c(0,1)))) stop("not a binary sequence") res <- sum(y*2^((length(y):1) - 1)) return(res) } 
+2
source

Source: https://habr.com/ru/post/974116/


All Articles