What would be the easiest way to convert a number to base 2 (in a string, as for example 5 would be converted to "0000000000000101") in R? There is intToBits, but it returns a vector of strings rather than a string:
> intToBits(12)
[1] 00 00 01 01 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
I have tried some other functions, but had no success:
> toString(intToBits(12))
[1] "00, 00, 01, 01, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00"
Note that
intToBits()returns a ‘raw’ vector, not a character vector (strings). Note that my answer is a slight extension of @nico’s original answer that removes the leading “0” from each bit:To break down the steps, for clarity:
Or, as @nico showed, we can use
as.integer()as a more concise way to remove the leading zero from each bit.Just for copy-paste convenience, here’s a function version of the above: