Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting decimal to binary in R?

Tags:

r

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" 
like image 273
Jay Avatar asked Jul 07 '11 16:07

Jay


People also ask

How to convert decimal to binary in R?

Example: Binary to Decimal In this program, we convert decimal number entered by the user into binary using a recursive function. Decimal number is converted into binary by dividing the number successively by 2 and printing the remainder in reverse order.

What is an A in binary code?

Let's look at binary codes for all letters of the English alphabet to give you an idea of how to write functions in code: A: 01000001. B: 01000010. C: 01000011. D: 01000100.


2 Answers

paste(rev(as.integer(intToBits(12))), collapse="") does the job

paste with the collapse parameter collapses the vector into a string. You have to use rev to get the correct byte order though.

as.integer removes the extra zeros

like image 83
nico Avatar answered Oct 03 '22 04:10

nico


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:

paste(sapply(strsplit(paste(rev(intToBits(12))),""),`[[`,2),collapse="") [1] "00000000000000000000000000001100" 

To break down the steps, for clarity:

# bit pattern for the 32-bit integer '12' x <- intToBits(12) # reverse so smallest bit is first (little endian) x <- rev(x) # convert to character x <- as.character(x) # Extract only the second element (remove leading "0" from each bit) x <- sapply(strsplit(x, "", fixed = TRUE), `[`, 2) # Concatenate all bits into one string x <- paste(x, collapse = "") x # [1] "00000000000000000000000000001100" 

Or, as @nico showed, we can use as.integer() as a more concise way to remove the leading zero from each bit.

x <- rev(intToBits(12)) x <- paste(as.integer(x), collapse = "") # [1] "00000000000000000000000000001100" 

Just for copy-paste convenience, here's a function version of the above:

dec2bin <- function(x) paste(as.integer(rev(intToBits(x))), collapse = "") 
like image 27
5 revs, 3 users 56% Avatar answered Oct 03 '22 04:10

5 revs, 3 users 56%