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
?
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
?
You could use the
packBits
function (in thebase
package). Bear in mind that this function requires very specific input.There is also the
strtoi
function (also in thebase
package):Here is what you can try:
That is, you can input both strings (because of
as.character()
) and numeric binary values but there are some problems with large numbers likebinNum
. 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. FunctiondigitsBase()
from packagesfsmisc
returns such a vector:Finally, another possibility is package
compositions
, for example:This function calculates the decimal version with a flexible base. Base equals 2 is binary, etc. This should work up until a base of 10.
In the case that you have binary string, all of the prior answers are great. I often find myself in situations where I want to encode a combination of binary vectors. The logic of translating from a combination of 0's and 1's to an integer is always the same:
Where B is a matrix, and each column is a binary vector.
Example: