package com.base.datarecovery.utils

/**
 * Author: nxl
 * Created on 2021/11/8 15:08
 * Email: niexueliang@qdtgkj.com
 * DESC: Hex码
 */
private const val HEXES = "0123456789ABCDEF"

/**
 * ByteArray转Hex码
 */
fun ByteArray.byteArrayToHexString(): String {
    val hex = StringBuilder(2 * this.size)
    for (element in this) {
        val high = element.toInt().and(0xFF).shr(4)
        val low = element.toInt().and(0x0F)
        hex.append(HEXES[high]).append(HEXES[low])
    }
    return hex.toString()
}

/**
 * HexString转ByteArray
 */
fun String.hexStringToByteArr(): ByteArray {
    val data = ByteArray(this.length / 2)
    for (i in this.indices step 2) {
        val character = this.substring(i, i + 2).toInt(16).toByte()
        data[i / 2] = character
    }
    return data
}