简体   繁体   中英

Convert binary vector to decimal

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.

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.

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.

If you'd like to stick to using compositions, just convert your vector to a string:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM