Skip to content

Instantly share code, notes, and snippets.

@nutterb
Created March 14, 2018 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nutterb/4084750cc8c28e85c2324a8dc26baea8 to your computer and use it in GitHub Desktop.
Save nutterb/4084750cc8c28e85c2324a8dc26baea8 to your computer and use it in GitHub Desktop.
Convert between number systems. Still incomplete
convert_to_decimal_single <- function(x, from = 2){
coll <- checkmate::makeAssertCollection()
checkmate::assert_integerish(x,
add = coll)
checkmate::assert_integerish(from,
len = 1,
lower = 1,
upper = 36
add = coll)
checkmate::reportAssertions(coll)
orig.scipen <- getOption("scipen")
options(scipen = ceiling(log10(x)))
on.exit(options(scipen = orig.scipen))
place <- unlist(strsplit(as.character(x), ""))
place <- as.numeric(place)
exp <- seq(length(place) - 1, 0, by = -1)
sum(place * from ^ exp)
}
convert_from_decimal_single <- function(x, to = 2){
coll <- checkmate::makeAssertCollection()
checkmate::assert_integerish(x,
add = coll)
checkmate::assert_integerish(to,
len = 1,
lower = 1,
upper = 36
add = coll)
checkmate::reportAssertions(coll)
digit <- c(0:9, LETTERS)[1:to]
result <- character(ceiling(logb(x, to)))
quotient <- x %/% to
result[length(result)] <- digit[(x %% to) + 1]
i <- length(result) - 1
while(i > 0){
result[i] <- digit[(quotient %% to) + 1]
quotient <- quotient %/% to
i <- i - 1
}
paste0(result, collapse = "")
}
convert_any_single <- function(x, from = 10, to = 2){
coll <- checkmate::makeAssertCollection()
checkmate::assert_integerish(from,
len = 1,
lower = 1,
upper = 36
add = coll)
checkmate::reportAssertions(coll)
x <- convert_to_decimal(x, from = from)
convert_from_decimal(x, to = to)
}
convert_to_decimal <- function(x, from = 2){
vapply(x,
FUN = convert_to_decimal_single,
FUN.VALUE = numeric(1),
from = from)
}
convert_from_decimal <- function(x, to = 2){
vapply(x,
FUN = convert_from_decimal_single,
FUN.VALUE = character(1),
to = to)
}
convert_any <- function(x, from = 10, to = 2){
vapply(x,
FUN = convert_any_single,
FUN.VALUE = character(1),
from = from,
to = to)
}
convert_any(c(15235814, 10, 57), 10, 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment