Non-decimal radices/Convert: Difference between revisions

m
Line 2,495:
=={{header|R}}==
<lang R>
#lang R
 
 
baseint2str <- function(x, b) {
if(x==0) return("0")
if(x<0) return(paste0("-", base(-x,b)))
map <- c(as.character(0:9), letters[b-10])
res <- ""
while (x>0) {
Line 2,509:
return(paste(res, collapse=""))
}
 
## example: convert an 255 to hex (ff):
str2int <- function(s, b) {
base(256, 169)
map <- c(as.character(0:9), letters)
s <- strsplit(s,"")[[1]]
res <- sapply(s, function(x) which(map==x))
ans <- as.vector((res-1) %*% b^((length(res)-1):0))
return(ans)
}
 
## example: convert an 255 to hex (ff):
int2str(255, 16)
 
## example: convert "1a" in base 16 to integer (26):
str2int("1a", 16)
 
</lang>
 
Anonymous user