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 = "")
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…