转换二进制字符串二进制或十进制值 [英] Convert binary string to binary or decimal value
问题描述
有没有任何功能,二进制字符串转换成二进制或十进制值?
Is there any function to convert binary string into binary or decimal value?
如果我有一个二进制字符串 000101
,我应该怎么办把它转换成 5
?
If I have a binary string 000101
, what should I do to convert it into 5
?
推荐答案
下面是您可以尝试什么:
Here is what you can try:
binStr <- "00000001001100110000010110110111" # 20121015
(binNum <- 00000001001100110000010110110111) # 20121015
[1] 1.0011e+24
binVec <- c(1,0,1,0,0,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1) # 2670721
shortBin <- 10011010010 # 1234
BinToDec <- function(x)
sum(2^(which(rev(unlist(strsplit(as.character(x), "")) == 1))-1))
BinToDec(binStr)
[1] 20121015
BinToDec(binNum)
[1] 576528
BinToDec(binVec)
[1] 2670721
BinToDec(shortBin)
[1] 1234
也就是说,你可以输入两个字符串(因为 as.character()
)和数字的二进制值,但也存在一些问题,有大量像 binNum
。据我了解,你也想二进制字符串转换为数字二进制值,但遗憾的是没有这样的数据类型,至少在基础R上。
That is, you can input both strings (because of as.character()
) and numeric binary values but there are some problems with large numbers like binNum
. As I understand you also want to convert binary string to numeric binary values, but unfortunately there is no such data type at least in base R.
编辑:立即 BinToDec
也接受二元载体,这可能是大量的解决方案。功能 digitsBase()
从包装 sfsmisc
返回这样的载体:
Now BinToDec
also accepts binary vectors, which might be a solution for large numbers. Function digitsBase()
from package sfsmisc
returns such a vector:
(vec <- digitsBase(5, base= 2, 10))
Class 'basedInt'(base = 2) [1:1]
[,1]
[1,] 0
[2,] 0
[3,] 0
[4,] 0
[5,] 0
[6,] 0
[7,] 0
[8,] 1
[9,] 0
[10,] 1
BinToDec(vec)
[1] 5
最后,另一种可能是包组合
,例如:
(x <- unbinary("10101010"))
[1] 170
(y <- binary(x))
[1] "10101010"
这篇关于转换二进制字符串二进制或十进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!