I am trying to learn how to convert numbers to binary and back in R.
Suppose I have the following binary string:
binary_string = "1101000011000001"
I know how to convert this into base 10:
base::strtoi(binary_string, base = 2)
[1] 53441
Now, I am trying to learn how to convert 53441 back into binary
# https://stackoverflow.com/questions/12088080/how-to-convert-integer-number-into-binary-vector
number2binary = function(number, noBits) {
binary_vector = rev(as.numeric(intToBits(number)))
if(missing(noBits)) {
return(binary_vector)
} else {
binary_vector[-(1:(length(binary_vector) - noBits))]
}
}
> number2binary(53441)
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 1 1 0 0 0 0 0 1
paste0(number2binary(53441), collapse="")
My Question: Am I doing this correctly?
Thanks!
References: