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,955 questions

51,897 answers

573 users

How to convert a hex to a byte array in Kotlin

2 Answers

0 votes
fun hexStringToByteArray(hex: String): ByteArray {
    val len = hex.length
    val byteArray = ByteArray(len / 2)
    
    for (i in 0 until len step 2) {
        byteArray[i / 2] = ((Character.digit(hex[i], 16) shl 4) + Character.digit(hex[i + 1], 16)).toByte()
    }
    
    return byteArray
}


fun main() {
    val hexString = "1A2D3E4F"
    val byteArray = hexStringToByteArray(hexString)
    
    println(byteArray.joinToString(" ") { it.toString() })
}


   
/*
run:

26 45 62 79
 
*/

 



answered Feb 15, 2025 by avibootz
0 votes
fun main() {
    val hexString = "1A2D3E4F"
    
    val bytes = hexString.chunked(2)
                         .map { it.toInt(16).toByte() }

    println(bytes)
}


   
/*
run:

[26, 45, 62, 79]
 
*/

 



answered Feb 15, 2025 by avibootz

Related questions

2 answers 104 views
2 answers 99 views
1 answer 71 views
1 answer 103 views
1 answer 75 views
75 views asked Nov 19, 2024 by avibootz
...