Convierta una cadena en una matriz de bytes y luego vuelva a la cadena original


¿Es posible convertir una cadena a matriz de bytes y luego volver a convertirla a la cadena original en Java o Android?

Mi objetivo es enviar algunas cadenas a un microcontrolador (Arduino) y almacenarlas en EEPROM (que es solo 1 KB). Traté de usar un hash MD5, pero parece que es solo un cifrado de una forma. ¿Qué puedo hacer para lidiar con este problema?

Author: Peter Mortensen, 2011-10-31

5 answers

Sugeriría usar los miembros de string, pero con una codificación explícita :

byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");

Mediante el uso de una codificación explícita (y una que soporta todo Unicode) se evitan los problemas de solo llamar a text.getBytes() etc:

  • Está utilizando explícitamente una codificación específica, por lo que sabe qué codificación usar más adelante, en lugar de confiar en el valor predeterminado de la plataforma.
  • Sabes que soportará todo Unicode (en oposición a, digamos, ISO-Latin-1).

EDITAR: Incluso aunque UTF-8 es la codificación predeterminada en Android, definitivamente sería explícito sobre esto. Por ejemplo, esta pregunta solo dice "en Java o Android", por lo que es completamente posible que el código termine siendo utilizado en otras plataformas.

Básicamente dado que la plataforma Java normal puede tener diferentes codificaciones predeterminadas, creo que es mejor ser absolutamente explícito. He visto demasiadas personas usando la codificación predeterminada y perdiendo datos para correr ese riesgo.

EDITAR: En mi he olvidado mencionar que no tienes que usar el nombre de la codificación - puedes usar un Charset en su lugar. Usando Guayaba usaría realmente :

byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);
 97
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-30 21:47:11

Puedes hacerlo así.

Matriz de cadena a byte

String stringToConvert = "This String is 76 characters long and will be converted to an array of bytes";
byte[] theByteArray = stringToConvert.getBytes();

Http://www.javadb.com/convert-string-to-byte-array

Matriz de bytes a Cadena

byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
String value = new String(byteArray);

Http://www.javadb.com/convert-byte-array-to-string

 11
Author: Michell Bak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-30 21:19:50

Use [String.getBytes()][1] para convertir a bytes y use [String(byte[] data)][2] constructor para convertir de nuevo a cadena.

 3
Author: Szere Dyeri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-30 21:19:46

Mira esto, puedes usar Base85: Base85 aka ASCII85 java projects

Tenía la misma pregunta.

 2
Author: Mat B.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:12

Import java.io.FileInputStream; import java.io.ByteArrayOutputStream;

Flujo de archivos de clase pública { // write a new method that will provide a new Byte array, and where this generally reads from an input stream

public static byte[] read(InputStream is) throws Exception
{
    String path = /* type in the absolute path for the 'commons-codec-1.10-bin.zip' */;

    // must need a Byte buffer

    byte[] buf = new byte[1024 * 16]

    // we will use 16 kilobytes

    int len = 0;

    // we need a new input stream

    FileInputStream is = new FileInputStream(path);

    // use the buffer to update our "MessageDigest" instance

    while(true)
    {
        len = is.read(buf);
        if(len < 0) break;
        md.update(buf, 0, len);
    }

    // close the input stream

    is.close();

    // call the "digest" method for obtaining the final hash-result

    byte[] ret = md.digest();

    System.out.println("Length of Hash: " + ret.length);

    for(byte b : ret)
    {
        System.out.println(b + ", ");
    }

    String compare = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";

    String verification = Hex.encodeHexString(ret);

    System.out.println();

    System.out.println("===")

    System.out.println(verification);

    System.out.println("Equals? " + verification.equals(compare));

}

}

 0
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-27 04:25:17