Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将二进制向量转换为十进制_R_Binary_Decimal - Fatal编程技术网

R 将二进制向量转换为十进制

R 将二进制向量转换为十进制,r,binary,decimal,R,Binary,Decimal,我有一个二进制字符串的向量: a<-c(0,0,0,1,0,1) 这给出了正确的解决方案,但: 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) bit

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

a<-c(0,0,0,1,0,1)
这给出了正确的解决方案,但:

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

如果您仍然想使用该函数,则该函数会起作用。

如果您想继续使用合成,只需将向量转换为字符串:

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

a此函数将起作用

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

bintodec有一种线性解决方案:

Reduce(函数(x,y)x*2+y,a)

说明:

扩展
Reduce
的应用程序会产生如下结果:

Reduce(函数(x,y)x*2+y,c(0,1,0,1,0))=((0*2+1)*2+0)*2+1)*2+0=10

接下来的每一个新位,我们都会将迄今为止的累积值翻倍,然后再将下一位相加


另请参见
Reduce()
函数的说明。

添加了一个应用示例
library(compositions)
a <- c(0,0,0,1,0,1)
achar <- paste(a,collapse="")
unbinary(achar)
[1] 5
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)
}