I want to perform some calculations in base 3 and need to have addition subtraction in that base. eg. 2+2 should become 11 in base 3
In the package sfcmisc
there is a function called digitsBase
that does such conversion.
library(sfcmisc)
digitsBase(2+2,base = 3)
# Class 'basedInt'(base = 3) [1:1]
# [,1]
# [1,] 1
# [2,] 1
You may be able to use gmp
package
library(gmp)
as.character(x = as.bigz(2 + 2), b = 3)
#[1] "11"
Or write your own function. I modified the one from here
foo = function(dec_n, base){
BitsInLong = 64
Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (base < 2 | base > nchar(Digits)){
stop(paste("The base must be >= 2 and <= ", nchar(Digits)))
}
if (dec_n == 0){
return(0)
}
index = BitsInLong
currentNumber = abs(dec_n)
charArray = character(0)
while (currentNumber != 0){
remainder = as.integer(currentNumber %% base)
charArray = c(charArray, substr(Digits, remainder + 1, remainder + 1))
currentNumber = currentNumber/base
}
charArray = inverse.rle(with(rle(rev(charArray)), list(values = if(values[1] == "0"){values[-1]}else{values},
lengths = if(values[1] == "0"){lengths[-1]}else{lenghts})))
result = paste(charArray, collapse = "")
if (dec_n < 0){
result = paste("-", result)
}
return(result)
}
USE
foo(dec_n = 2+2, base = 3)
#[1] "11"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With