Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

r - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...