Anonymous user
Non-decimal radices/Convert: Difference between revisions
m
→{{header|R}}
m (→{{header|R}}) |
|||
Line 2,495:
=={{header|R}}==
<lang R>
if(x==0) return("0")
if(x<0) return(paste0("-", base(-x,b)))
map <- c(as.character(0:9), letters
res <- ""
while (x>0) {
Line 2,509:
return(paste(res, collapse=""))
}
## example: convert an 255 to hex (ff):▼
str2int <- function(s, b) {
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)
}
int2str(255, 16)
## example: convert "1a" in base 16 to integer (26):
str2int("1a", 16)
</lang>
|