stijnb1234
stijnb1234

Reputation: 184

Java: Converting byte string to byte array

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?

Upvotes: 2

Views: 13109

Answers (3)

Sandeepa
Sandeepa

Reputation: 3755

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 

Upvotes: 1

Rakirnd
Rakirnd

Reputation: 81

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 :).

Upvotes: 1

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

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");
    }

Upvotes: 3

Related Questions