将二进制向量转换为十进制 [英] 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.
我尝试使用compositions
包和unbinary()
函数,但是,此解决方案以及在此站点上发现的大多数其他解决方案都需要使用g-adic字符串作为输入参数.
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?
说明问题:
library(compositions)
unbinary("000101")
[1] 5
这提供了正确的解决方案,但是:
This gives the correct solution, but:
unbinary(a)
unbinary("a")
unbinary(toString(a))
产生NA.
推荐答案
您可以尝试使用此功能
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
这里我们跳过字符转换.这仅使用base
函数.
here we skip the character conversion. This only uses base
functions.
可能
unbinary(paste(a, collapse=""))
如果您仍然想使用该功能,该方法将奏效.
would have worked should you still want to use that function.
这篇关于将二进制向量转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!