Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,023 questions

51,974 answers

573 users

How to convert a number to any base in Scala

1 Answer

0 votes
object BaseConvert {

  def toBase(n: Int, base: Int): String = {
    val digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    require(base >= 2 && base <= 36, "Base must be between 2 and 36")

    if (n == 0) return "0"

    def loop(value: Int, acc: String): String = {
      if (value == 0) acc
      else {
        val remainder = value % base
        loop(value / base, digits(remainder).toString + acc)
        // Alternatively: loop(value / base, s"${digits(remainder)}$acc")
      }
    }

    loop(n, "")
  }

  def main(args: Array[String]): Unit = {
    val number = 255
    val bases = List(2, 8, 16, 36)

    bases.foreach { b =>
      println(s"$number in base $b = ${toBase(number, b)}")
    }
  }
}

  
  
  
/*
run:
  
255 in base 2 = 11111111
255 in base 8 = 377
255 in base 16 = FF
255 in base 36 = 73
  
*/

 

 



answered 4 hours ago by avibootz
...