-4

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="")

enter image description here

My Question: Am I doing this correctly?

Thanks!

References:

stats_noob
  • 5,401
  • 4
  • 27
  • 83

1 Answers1

1

First of all, you are doing right. Also, you can try

trimws(
  paste0(rev(as.integer(intToBits(53441))), collapse = ""), 
  "left", 
  "0"
)

which gives

"1101000011000001"
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • @ Thank you so much for your answer! I can also use this function to do the opposite? base::strtoi(binary_string, base = 2) – stats_noob Mar 11 '23 at 17:02