https://kotlinlang.org logo
#stdlib
Title
# stdlib
m

marcinmoskala

06/19/2017, 1:40 PM
true
Copy code
import org.testng.annotations.Test
import sun.rmi.runtime.Log
import java.util.*
import kotlin.experimental.and

private val hexArray = "0123456789abcdef".toCharArray()
fun ByteArray.toHexString1(): String {
    val hexChars = CharArray(size * 2)
    for (num in indices) {
        val v = this[num].toInt() and 0xFF
        hexChars[num * 2] = hexArray[v.ushr(4)]
        hexChars[num * 2 + 1] = hexArray[v and 0x0F]
    }
    return String(hexChars)
}

fun ByteArray.toHexString2(): String {
    val sb = StringBuilder(size * 2)
    forEach { b -> sb.append(String.format("%02x", b)) }
    return sb.toString()
}

fun ByteArray.toHexString3() = joinToString("") { byte -> Integer.toString((byte.toInt() and 0xFF) + 0x100, 16).substring(1) }

fun ByteArray.toHexString4() = joinToString("") { byte -> "%02x".format(byte) }

fun ByteArray.toHexString5(): String {
    val buffer = StringBuffer(size * 2)
    for (num in indices) {
        val v = this[num].toInt() and 0xFF
        buffer.append(hexArray[v.ushr(4)])
        buffer.append(hexArray[v and 0x0F])
    }
    return buffer.toString()
}

fun main(args: Array<String>) {
    val byteArrayExamples: List<ByteArray> = (1..1000).map { randomByteArray() }
    measureTime { byteArrayExamples.map { it.toHexString1() } }
    measureTime { byteArrayExamples.map { it.toHexString2() } }
    measureTime { byteArrayExamples.map { it.toHexString3() } }
    measureTime { byteArrayExamples.map { it.toHexString4() } }
    measureTime { byteArrayExamples.map { it.toHexString5() } }
}

class ByteArrayToHexString() {

    private val byteArrayExamples: List<ByteArray> = (1..100).map { randomByteArray() }

    @Test fun resultsAreTheSame() {
        val results1 = byteArrayExamples.map { it.toHexString1() }
        val results2 = byteArrayExamples.map { it.toHexString2() }
        val results3 = byteArrayExamples.map { it.toHexString3() }
        val results4 = byteArrayExamples.map { it.toHexString4() }
        val results5 = byteArrayExamples.map { it.toHexString5() }
        assert(results1 == results2)
        assert(results2 == results3)
        assert(results3 == results4)
        assert(results4 == results5)
    }

}

private val random = Random()

private fun randomByteArray(): ByteArray {
    val byteArray = ByteArray(2000)
    random.nextBytes(byteArray)
    return byteArray
}
It took 18 It took 1518 It took 123 It took 1137 It took 44
2 Views