package com.korancrew.brizzi.hce

private val HEX_CHARS = "0123456789ABCDEF".toCharArray()

/** Convert byte[] ke string hex uppercase tanpa spasi (tanpa pemisah). */
fun ByteArray.toHex(): String {
    val result = StringBuilder(size * 2)
    forEach { byte ->
        val value = byte.toInt() and 0xFF
        result.append(HEX_CHARS[value ushr 4])
        result.append(HEX_CHARS[value and 0x0F])
    }
    return result.toString()
}

/** Convert string hex uppercase ke byte[], melempar jika panjang hex ganjil. */
fun String.hexToBytes(): ByteArray {
    val normalized = replace(" ", "").uppercase()
    require(normalized.length % 2 == 0) { "Hex string length must be even" }
    return ByteArray(normalized.length / 2) { index ->
        val offset = index * 2
        normalized.substring(offset, offset + 2).toInt(16).toByte()
    }
}
