Skip to content

Instantly share code, notes, and snippets.

@OldLipe
Last active May 2, 2019 14:43
Show Gist options
  • Save OldLipe/2ea5a0dff7ae51a75c230be6a35f0056 to your computer and use it in GitHub Desktop.
Save OldLipe/2ea5a0dff7ae51a75c230be6a35f0056 to your computer and use it in GitHub Desktop.
#'@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