1 /* 2 * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 */ 4 5 package kotlinx.serialization.test 6 7 object InternalHexConverter { 8 private const val hexCode = "0123456789ABCDEF" 9 parseHexBinarynull10 fun parseHexBinary(s: String): ByteArray { 11 val len = s.length 12 require(len % 2 == 0) { "HexBinary string must be even length" } 13 val bytes = ByteArray(len / 2) 14 var i = 0 15 16 while (i < len) { 17 val h = hexToInt(s[i]) 18 val l = hexToInt(s[i + 1]) 19 require(!(h == -1 || l == -1)) { "Invalid hex chars: ${s[i]}${s[i+1]}" } 20 21 bytes[i / 2] = ((h shl 4) + l).toByte() 22 i += 2 23 } 24 25 return bytes 26 } 27 hexToIntnull28 private fun hexToInt(ch: Char): Int = when (ch) { 29 in '0'..'9' -> ch - '0' 30 in 'A'..'F' -> ch - 'A' + 10 31 in 'a'..'f' -> ch - 'a' + 10 32 else -> -1 33 } 34 printHexBinarynull35 fun printHexBinary(data: ByteArray, lowerCase: Boolean = false): String { 36 val r = StringBuilder(data.size * 2) 37 for (b in data) { 38 r.append(hexCode[b.toInt() shr 4 and 0xF]) 39 r.append(hexCode[b.toInt() and 0xF]) 40 } 41 return if (lowerCase) r.toString().lowercase() else r.toString() 42 } 43 toHexStringnull44 fun toHexString(n: Int): String { 45 val arr = ByteArray(4) 46 for (i in 0 until 4) { 47 arr[i] = (n shr (24 - i * 8)).toByte() 48 } 49 return printHexBinary(arr, true).trimStart('0').takeIf { it.isNotEmpty() } ?: "0" 50 } 51 } 52