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.

39,890 questions

51,821 answers

573 users

How to convert from HEX color to RGB in Kotlin

2 Answers

0 votes
fun hexToRgb(hex: String): Triple<Int, Int, Int> {
    val color = hex.removePrefix("#")
    require(color.length == 6) { "Invalid hex color format" }
    
    val r = color.substring(0, 2).toInt(16)
    val g = color.substring(2, 4).toInt(16)
    val b = color.substring(4, 6).toInt(16)
    
    return Triple(r, g, b)
}

fun main() {
	val hexColor = "#FFA805"
	val (r, g, b) = hexToRgb(hexColor)
	
    println("RGB: ($r, $g, $b)")  
}

  
     
/*
run:
  
RGB: (255, 168, 5)
 
*/

 



answered Mar 7, 2025 by avibootz
0 votes
fun hexToRgb(hex: String): Triple<Int, Int, Int> {
    var color = hex.removePrefix("#")

    if (color.length == 3) {
        color = color.flatMap { "$it$it".toList() }.joinToString("")
    }

    require(color.length == 6) { "Invalid hex color format" }

    val r = color.substring(0, 2).toInt(16)
    val g = color.substring(2, 4).toInt(16)
    val b = color.substring(4, 6).toInt(16)

    return Triple(r, g, b)
}

fun main() {
    val hexColor1 = "#FFA805"
    val (r1, g1, b1) = hexToRgb(hexColor1)
    println("RGB: ($r1, $g1, $b1)")

    val hexColor2 = "#f00"
    val (r2, g2, b2) = hexToRgb(hexColor2)
    println("RGB: ($r2, $g2, $b2)")
}
  
     
/*
run:
  
RGB: (255, 168, 5)
RGB: (255, 0, 0)
 
*/

 



answered Mar 7, 2025 by avibootz

Related questions

1 answer 70 views
1 answer 103 views
2 answers 71 views
2 answers 78 views
2 answers 84 views
...