ByteArrayUtils.kt (1717B)
1 /* 2 * This file is part of GNU Taler 3 * (C) 2020 Taler Systems S.A. 4 * 5 * GNU Taler is free software; you can redistribute it and/or modify it under the 6 * terms of the GNU General Public License as published by the Free Software 7 * Foundation; either version 3, or (at your option) any later version. 8 * 9 * GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY 10 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 * A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 * 13 * You should have received a copy of the GNU General Public License along with 14 * GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 17 package net.taler.common 18 19 object ByteArrayUtils { 20 21 private const val HEX_CHARS = "0123456789ABCDEF" 22 23 fun hexStringToByteArray(data: String): ByteArray { 24 val result = ByteArray(data.length / 2) 25 26 for (i in data.indices step 2) { 27 val firstIndex = HEX_CHARS.indexOf(data[i]) 28 val secondIndex = HEX_CHARS.indexOf(data[i + 1]) 29 30 val octet = firstIndex.shl(4).or(secondIndex) 31 result[i.shr(1)] = octet.toByte() 32 } 33 return result 34 } 35 36 37 private val HEX_CHARS_ARRAY = HEX_CHARS.toCharArray() 38 39 @Suppress("unused") 40 fun toHex(byteArray: ByteArray): String { 41 val result = StringBuffer() 42 43 byteArray.forEach { 44 val octet = it.toInt() 45 val firstIndex = (octet and 0xF0).ushr(4) 46 val secondIndex = octet and 0x0F 47 result.append(HEX_CHARS_ARRAY[firstIndex]) 48 result.append(HEX_CHARS_ARRAY[secondIndex]) 49 } 50 return result.toString() 51 } 52 53 }