Last active
May 2, 2019 14:43
-
-
Save OldLipe/2ea5a0dff7ae51a75c230be6a35f0056 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#'@authors Adriano and Felipe Carvalho | |
#' | |
#'@description Maybe this code may convert for any base | |
#' | |
#'@param valor value to be converted | |
#' | |
#'@param base base for value to to be converted | |
#' | |
#'@param base_req the base you want to convert | |
#' | |
#'@example | |
#'conversor_base("10010", 2, 19) | |
conversor_decimal <- function(valor, base) { | |
resultado <- 0 | |
tamanho <- (nchar(valor) - 1) | |
for (i in 1:(nchar(valor))) { | |
if (is.na(suppressWarnings(as.numeric(substr(valor, i, i))))) { | |
numerico <- strtoi(substr(valor, i, i), base) | |
} else { | |
numerico <- as.integer(substr(valor, i, i)) | |
} | |
resultado = resultado + numerico * base ^ tamanho | |
tamanho = tamanho - 1 | |
} | |
return(resultado) | |
} | |
conversor_base <- function(valor, base, base_req) { | |
base_10 <- conversor_decimal(valor, base) | |
resultado <- c() | |
while (base_10 > 0) { | |
resultado <- c(resultado, base_10 %% base_req) | |
base_10 = as.integer(base_10 / base_req) | |
} | |
resultado <- | |
lapply(resultado, function(x) { | |
ifelse(x >= 10, return(toupper(letters[x - 10 + 1])), return(as.character(x))) | |
}) | |
return(unlist(rev(resultado))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment