Convert binary string to binary or decimal value

LifeWorks picture LifeWorks · Oct 15, 2012 · Viewed 23.5k times · Source

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?

Answer

BenBarnes picture BenBarnes · Oct 15, 2012

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