将二进制向量转换为十进制 [英] Convert binary vector to decimal

查看:85
本文介绍了将二进制向量转换为十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二进制字符串的向量:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆