net.dankito.utils.hashing.HexConverter.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-utils Show documentation
Show all versions of java-utils Show documentation
Some basic utils needed in many projects
The newest version!
package net.dankito.utils.services.hashing
import kotlin.experimental.and
open class HexConverter {
companion object {
protected val hexArray = "0123456789ABCDEF".toCharArray()
fun byteArrayToHexString(bytes: ByteArray): String {
val hexChars = CharArray(bytes.size * 2)
for (j in bytes.indices) {
// see http://kotlinlang.org/docs/reference/basic-types.html #Operations
val v = bytes[j].and(0xFF.toByte()).toInt()
hexChars[j * 2] = hexArray[v ushr(4)]
hexChars[j * 2 + 1] = hexArray[v.and(0x0F)]
}
return String(hexChars)
}
}
open fun hexStringToByteArray(hexString: String): ByteArray {
val bytes = ByteArray(hexString.length / 2)
for (i in bytes.indices) {
val index = i * 2
val v = Integer.parseInt(hexString.substring(index, index + 2), 16)
bytes[i] = v.toByte()
}
return bytes
}
@JvmOverloads
open fun byteArrayToHexStringViaStringFormat(bytes: ByteArray, bytesSeparator: String? = ""): String {
val bytesSeparatorVar = bytesSeparator ?: ""
val stringBuilder = StringBuilder()
for (singleByte in bytes) {
stringBuilder.append(String.format("%02X" + bytesSeparatorVar, singleByte))
}
stringBuilder.replace(stringBuilder.length - bytesSeparatorVar.length, stringBuilder.length, "")
return stringBuilder.toString()
}
}