2

I want to convert my byte[] to a String, and then convert that String to a byte[].

So,

byte[] b = myFunction();
String bstring = b.toString();
/* Here the methode to convert the bstring to byte[], and call it ser */
String deser = new String(ser);

bstring gives me [B@74e752bb.

And then convert the String to byte[]. I'm not using it in this order, but this is an example.

How do I need to do this in Java?

stijnb1234
  • 184
  • 4
  • 19

3 Answers3

3

When converting byte[] to String, you should use this,

new String(b, "UTF-8");

instead of,

b.toString();

When you are converting byte array to String, you should always specify a character encoding and use the same encoding while converting back to byte array from String. Best is to use UTF-8 encoding as that is quite powerful and compact encoding and can represent over a million characters. If you don't specify a character encoding, then platform's default encoding may be used which may not be able to represent all characters properly when converted from byte array to String.

Your method when dealt appropriately, should be written something like this,

    public static void main(String args[]) throws Exception {
        byte[] b = myFunction();
//      String bstring = b.toString(); // don't do this
        String bstring = new String(b, "UTF-8");
        byte[] ser = bstring.getBytes("UTF-8");
        /* Here the methode to convert the bstring to byte[], and call it ser */
        String deser = new String(ser, "UTF-8");
    }
Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36
  • I just want to have a save way to hash a string to save it in a yaml file, and that I can decrypt it. – stijnb1234 Nov 10 '18 at 15:24
  • If you want to save byte[] as it is, in some yaml file, you can use FileOutputStream to write bytes into a file. I am not sure what you mean by "save way to hash" Can you elaborate it a bit? Converting byte[] to String using b.toString() may not give you a particular string. – Pushpesh Kumar Rajwanshi Nov 10 '18 at 15:25
  • Sorry, I mean this: It works, but I want to save the byte[] on a safe way in a yaml file, and now I'm saving only the old string. – stijnb1234 Nov 10 '18 at 15:29
  • How are you saving it in safe way in yaml file? See if you can use base64 to just encode your byte array, as that will give you physical printable string version of your byte array. – Pushpesh Kumar Rajwanshi Nov 10 '18 at 15:38
1

I am no expert, but you should try the methods provided by the "Byte" class and if necessary, some loops. Try byte b = Byte.parseByte(String s) to convert a string to a byte and String s = Byte.toString(byte b) to convert a byte to a string. Hope this helps :).

Rakirnd
  • 81
  • 4
1

You can do it like this,

String string = "Your String";
byte[] bytesFromString = string.getBytes(); // get bytes from a String
String StringFromByteArray = new String(bytesFromString); // get the String from a byte array 
Sandeepa
  • 3,457
  • 5
  • 25
  • 41