I try with a friend to code a general function to convert between binary and decimal inputs.
conversion <- function(number, direction = c("to_dec", "to_bin")) {
direction <- match.arg(direction)
if(grepl("[2-9]", as.character(number), ""[[1L]]) &
direction == "to_dec" &typeof(number)=='character') {
warning(paste0("Non-binary digits in number. Argument direction changed.,Continue with conversion to binary number."))
direction <- "to_dec" } else {
stop(paste0(
"Binary number not supplied as string. Leading 0s get lost.\n", "Stop conversion."))
}
if(direction == "to_dec") {
u <- as.numeric(strsplit(as.character(number), "")[[1L]])
ret <- 0L
u <- rev(u)
for(i in 1:length(u)){
ret <- ret + u[i] * 2L^(i - 1L) }
ret <- as.integer(ret) } else {
u <- as.integer(number)
ret <- vector(mode = "integer") while (u > 1) {
ret <- c(ret, u%%2)
floor(u / 2) }
ret <- paste(ret)
}
ret
}
That's how the code looks like. However we are not too sure about the if statements and thus get some errors. If someone has an input idea, let us know.
Aucun commentaire:
Enregistrer un commentaire