groovy

How to convert a value to base 16 or base 2 or decimal in groovy?


I need to implement a function toBase(a,b) where 'b' is the value which needs to be converted to the base 'a' in groovy. Need help on this function.


Solution

  • def toBase(a, b) {
        if (a < 2 || a > 36) {
            throw new IllegalArgumentException("Base must be between 2 and 36")
        }
    
        String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        def result = ""
        
        while (b > 0) {
            int remainder = b % a
            result = digits[remainder] + result
            b = b.intdiv(a)
        }
        
        return result == "" ? "0" : result
    }
    
    println toBase(2, 255)   // Binary representation of 255 -> 11111111
    println toBase(16, 255)  // Hexadecimal representation of 255 -> FF