Convert binary vector to decimal

五迷三道 提交于 2019-12-05 07:03:00

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)
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!