Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert binary string to binary or decimal value

Is there any function to convert binary string into binary or decimal value?

If I have a binary string 000101, what should I do to convert it into 5?

like image 658
LifeWorks Avatar asked Oct 15 '12 09:10

LifeWorks


3 Answers

You could use the packBits function (in the base package). Bear in mind that this function requires very specific input.

(yy <- intToBits(5))
#  [1] 01 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
# [26] 00 00 00 00 00 00 00
# Note that there are 32 bits and the order is reversed from your example

class(yy)
[1] "raw"

packBits(yy, "integer")
# [1] 5

There is also the strtoi function (also in the base package):

strtoi("00000001001100110000010110110111", base = 2)
# [1] 20121015

strtoi("000101", base = 2)
# [1] 5
like image 128
BenBarnes Avatar answered Oct 23 '22 10:10

BenBarnes


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

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.

Edit: 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

Finally, another possibility is package compositions , for example:

(x <- unbinary("10101010"))
[1] 170
(y <- binary(x))
[1] "10101010"
like image 28
Julius Vainora Avatar answered Oct 23 '22 09:10

Julius Vainora


base::strtoi(binary_string, base = 2)
like image 16
Justin Howe Avatar answered Oct 23 '22 10:10

Justin Howe