English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Para convertir una cadena hexadecimal en un array de bytes, primero debes obtener la longitud de la cadena dada y incluirla en la creación del nuevo array de bytes.
byte[] val = new byte[str.length() / 2];
Ahora, realiza un bucle for hasta la longitud del array de bytes.
for (int i = 0; i < val.length;++) { int index = i * 2; int j = Integer.parseInt(str.substring(index, index + 2), 16); val[i] = (byte) j; }
Veamos un ejemplo completo.
public class Demo { public static void main(String args[]) { String str = "p"; byte[] val = new byte[str.length() / 2]; for (int i = 0; i < val.length;++) { int index = i * 2; int j = Integer.parseInt(str.substring(index, index + 2), 16); val[i] = (byte) j; } System.out.println(val); } }
Resultado de salida
[B@2a139a55