Generalidades

Función para convertir una cadena hexadecimal a una matriz de bytes en Android Studio | Autor: Purnami Indryaswari | Diciembre de 2021

Purnami Indryaswari

Esta función convierte una cadena hexadecimal en una matriz de bytes en Kotlin:

fun String.toBytes(): ByteArray {
check(length % 2 == 0) { "Must have an even length" }

return chunked(2)
.map { it.toInt(16).toByte() }
.toByteArray()
}

O así:

fun hexStringToByteArray(s: String): ByteArray? {
val len = s.length
val data = ByteArray(len / 2)
var i = 0
while (i < len) {
data[i / 2] =
((Character.digit(s[i], 16) shl 4) + Character.digit(s[i + 1], 16)).toByte()
i += 2
}
return data
}

Esto está convirtiendo la matriz de bytes en una cadena hexadecimal en Kotlin:

fun ByteArray.toHexString() = joinToString("") { "%02x".format(it) }

O así:

fun bytesToHexString(bArray: ByteArray?): String? {
if (bArray == null) {
return null
}
val sb = StringBuffer(bArray.size)
var sTemp: String
var j = 0
for (i in bArray.indices) {
sTemp = Integer.toHexString(0xFF and bArray[i].toInt())
if (sTemp.length < 2) sb.append(0)
sb.append(sTemp.toUpperCase())
j++
}
return sb.toString()
}

Este es un byte a cadena hexadecimal:

fun byteToHexString(b: Byte): String? {
val n: Int = b.toInt() and 0x000000FF
val result = (if (n < 0x00000010) "0" else "") + Integer.toHexString(n)
return result.toUpperCase()
}

Esta función convierte una cadena hexadecimal en una matriz de bytes en Java:

public static byte[] hexStringToBytes(String text)
throws NumberFormatException {
if (text == null) { return null; }
StringBuffer hexText = new StringBuffer();
for (int i=0; i < text.length(); i++) {
char c = text.charAt(i);
if (Character.isWhitespace(c)) {
continue;
} else if (HEXCHARS.indexOf(c) < 0) {
throw new NumberFormatException();
} else {
hexText.append(c);
}
}
if (hexText.length() % 2 != 0) {
hexText.insert(0,"0");
}
byte[] result = new byte[hexText.length() / 2];
for (int i = 0; i < hexText.length(); i += 2) {
int hi = hexDigitToInt(hexText.charAt(i));
int lo = hexDigitToInt(hexText.charAt(i + 1));
result[i / 2] = (byte)(((hi & 0x000000FF) << 4) | (lo & 0x000000FF));
}
return result;
}

O así:

public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}

Esta función convierte una matriz de bytes en una cadena hexadecimal en Java:

public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}

LEER  Conceptos básicos de Kotlin # 2. Conceptos básicos de KOTLIN Parte 2 🎉 Continuemos ... | de No soy un programador. | Noviembre 2021

Publicaciones relacionadas

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Botón volver arriba