Decimal to Binary Conversion in R – Loop, Recursion, Vector Logic & Built-in
Learn how to convert decimal numbers to binary in R using four different techniques, each demonstrating a new way of thinking in R's syntax and logic style.
Where It’s Useful
-
Data science tasks where binary encoding is required
-
Learning base conversion logic in R
-
Teaching number systems in programming education
-
Writing utility functions for numeric preprocessing
Binary Conversion Using While Loop
# Convert decimal to binary using a basic while loop
decimal_to_binary_loop <- function(num) {
if (num == 0) return("0")
binary <- ""
while (num > 0) {
binary <- paste0(num %% 2, binary)
num <- num %/% 2
}
return(binary)
}
cat("Binary of 19:", decimal_to_binary_loop(19), "\n")
How It Works
-
%/%
divides the number and drops decimals (integer division) -
%%
gives the remainder -
Use
paste0()
to build the binary string by prepending digits
Output
Binary of 19: 10011
Recursive Binary Conversion
# Convert decimal to binary using recursion
decimal_to_binary_recursive <- function(num) {
if (num == 0) return("")
return(paste0(decimal_to_binary_recursive(num %/% 2), num %% 2))
}
binary <- decimal_to_binary_recursive(23)
cat("Binary of 23:", ifelse(nchar(binary) == 0, "0", binary), "\n")
How It Works
-
Function calls itself with the number divided by 2.
-
On return, appends the remainder
(num %% 2)
. -
Special handling for
0
withifelse()
.
Output
Binary of 23: 10111
Vector-Based Conversion Logic
# Convert decimal to binary using vectorized logic
decimal_to_binary_vector <- function(num) {
if (num == 0) return("0")
bits <- c()
while (num > 0) {
bits <- c(num %% 2, bits)
num <- num %/% 2
}
return(paste(bits, collapse = ""))
}
cat("Binary of 30:", decimal_to_binary_vector(30), "\n")
How It Works
-
Creates a vector
bits
and prepends each binary digit. -
paste(..., collapse = "")
joins the vector into a string.
Output
Binary of 30: 11110
Built-in Conversion using intToBits()
# Using intToBits() to get binary and trimming unused zeros
decimal_to_binary_builtin <- function(num) {
bits <- intToBits(num)[1:32]
binary <- paste(rev(as.integer(bits)), collapse = "")
binary_trimmed <- sub("^0+", "", binary) # remove leading zeros
return(ifelse(nchar(binary_trimmed) == 0, "0", binary_trimmed))
}
cat("Binary of 10:", decimal_to_binary_builtin(10), "\n")
How It Works
-
intToBits()
returns a raw bit array (32 bits). -
Convert each bit to integer and reverse.
-
Trim leading zeros using
sub()
.
Output
Binary of 10: 1010
Summary
You’ve just learned four powerful and clean ways to convert decimal numbers into binary using R. Each method — from classic loops and recursion to vector manipulation and intToBits()
— offers a new angle to understand how binary conversion works in a statistical programming language like R.