Convert Java Byte Array - String - Byte Array

+2 votes

I am trying to understand a byte[] to string, a string representation of byte[] to byte[] conversion. I convert my byte[] to a string to send, I then expect my web service (written in python) to echo the data straight back to the client.

When I send the data:

Arrays.toString(data.toByteArray())

Bytes to send:

[B@405217f8

Send (This is the result of Arrays.toString() which should be a string representation of my byte data, this data will be sent across the wire):

[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]

On the python side, the python server returns a string to the caller (which I can see is the same as the string I sent to the server

[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]

The server should return this data to the client, where it can be verified.

The response my client receives (as a string) looks like

[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]

I can't seem to figure out how to get the received string back into a byte[]

Whatever I seem to try I end up getting a byte array which looks as follows...

[91, 45, 52, 55, 44, 32, 49, 44, 32, 49, 54, 44, 32, 56, 52, 44, 32, 50, 44, 32, 49, 48, 49, 44, 32, 49, 49, 48, 44, 32, 56, 51, 44, 32, 49, 49, 49, 44, 32, 49, 48, 57, 44, 32, 49, 48, 49, 44, 32, 51, 50, 44, 32, 55, 56, 44, 32, 55, 48, 44, 32, 54, 55, 44, 32, 51, 50, 44, 32, 54, 56, 44, 32, 57, 55, 44, 32, 49, 49, 54, 44, 32, 57, 55, 93]

or a byte representation which is as follows:

B@2a80d889

What am I doing wrong here?

May 15, 2018 in Java by sharth
• 3,320 points
3,202 views

10 answers to this question.

0 votes

You can't just take the returned string and construct a string from it...It is not a byte[] data type now, it is already a string; you need to parse it. For example :

String response = "[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]";      // response from the Python script

String[] byteValues = response.substring(1, response.length() - 1).split(",");
byte[] bytes = new byte[byteValues.length];

for (int i=0, len=bytes.length; i<len; i++) {
   bytes[i] = Byte.parseByte(byteValues[i].trim());     
}

String str = new String(bytes);

You get a hint of your problem in your question, where you say "Whatever I seem to try I end up getting a byte array which looks as follows... [91, 45, ...", because 91 is the byte value for [, so [91, 45, ... is the byte array of the string "[-45, 1, 16, ..." string.

The method Arrays.toString() will return a String representation of the specified array; meaning that the returned value will not be an array anymore. For example :

byte[] b1 = new byte[] {97, 98, 99};

String s1 = Arrays.toString(b1);
String s2 = new String(b1);

System.out.println(s1);        // -> "[97, 98, 99]"
System.out.println(s2);        // -> "abc";

Now, you can see, s1 holds the string representation of the array b1, while s2 holds the string representation of the bytes contained in b1.

In our problem, your server returns a string similar to s1, therefore to get the array representation back, you need the opposite constructor method. If s2.getBytes() is the opposite of new String(b1), you need to find the opposite of Arrays.toString(b1), thus the code I posted in the first snippet of this answer.

answered May 15, 2018 by sharth
• 3,320 points
0 votes
String coolString = "cool string";

byte[] byteArray = coolString.getBytes();

String reconstitutedString = new String(byteArray);

System.out.println(reconstitutedString);
answered Aug 2, 2018 by Sushmita
• 6,880 points
+2 votes

Character Stream Vs Byte Stream

  1. Character oriented are tied to datatype. Only string type or character type can be read through it while byte oriented are not tied to any datatype, data of any datatype can be read(except string) just you have to specify it.
     
  2. Character oriented reads character by character while byte oriented reads byte by byte.
     
  3. Character oriented streams use character encoding scheme(UNICODE) while byte oriented do not use any encoding scheme.
     
  4. Character oriented streams are also known as reader and writer streams Byte oriented streams are known as data streams-Data input stream and Data output stream. 
answered Sep 25, 2018 by carldivin
• 180 points
+1 vote
public class bytetoarray {
     public static void main(String[] args) {
          byte ba[] = { 'N', 'A', 'B', 'A', 'R', 'U', 'P', 'A' };
          byte ba1[] = { 78, 65, 66, 65, 82, 85, 80, 65 };
          String str = new String(ba);
          String str1 = new String(ba1);
          System.out.println(str);
          System.out.println(str1);
     }
}
answered Dec 10, 2018 by Nabarupa
0 votes
String s = bytes.toString();

Use this and thats it.
answered Dec 10, 2018 by Pankaj
0 votes

Use the following syntax for converting byte array to string, here byte states the array name.

String s = new String(bytes);
answered Dec 10, 2018 by Roushan
0 votes

There are two ways you can do it.

  1. By creating new String Object and assign byte[] to it.
  2. Best way to do this via “UTF-8” decoding.
answered Dec 10, 2018 by Nabarupa
0 votes
try {
decodedDataUsingUTF8 = new String(bytesData, "UTF-8");  // Best way to decode using "UTF-8"
    System.out.println("Text Decryted using UTF-8 : " + decodedDataUsingUTF8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

Use this

answered Dec 10, 2018 by rajesh
0 votes

Try this:

String s = new String(bytes);
answered Dec 10, 2018 by Naman
0 votes
String srt = "yourstring";
byte[] byteArray = str.getBytes();
String tmpstr = new String(byteArray);
System.out.println(tmpstr);

Hope this helps.

answered Dec 10, 2018 by Rahul

Related Questions In Java

0 votes
2 answers

How can I convert byte array into hex string in Java?

public static String byteArrayToHex(byte[] a) { ...READ MORE

answered Aug 29 in Java by Sirajul
• 25,420 points
385 views
0 votes
2 answers

How to convert a java string into byte array

Try using String.getBytes(). It returns a byte[] ...READ MORE

answered Aug 22 in Java by Sirajul
• 25,420 points
54 views
0 votes
1 answer

How to convert a string representation of a hex dump to a byte array using Java?

public static byte[] hexStringToByteArray(String s) { ...READ MORE

answered Sep 26, 2018 in Java by sharth
• 3,320 points
153 views
0 votes
2 answers

How to convert an int array to string using tostring method in java?

Use java.util.Arrays: String res = Arrays.toString(array); System.o ...READ MORE

answered Aug 16 in Java by Sirajul
• 25,420 points
206 views
0 votes
2 answers

How can I convert a String variable to a primitive int in Java

 Here are two ways illustrating this: Integer x ...READ MORE

answered Aug 20 in Java by Sirajul
• 25,420 points
132 views
0 votes
2 answers
0 votes
2 answers
0 votes
3 answers

How to convert File to Byte[] in Java?

import java.io.File; import java.nio.file.Files; File file; // ...(file is initialised)... byte[] ...READ MORE

answered Aug 14, 2018 in Java by samarth295
• 2,190 points
68 views
0 votes
1 answer

Convert String type to byte[] in Java

Try using String.getBytes(). It returns a byte[] ...READ MORE

answered May 8, 2018 in Java by Rishabh
• 3,540 points
73 views
0 votes
2 answers

How to convert byte array to String and STring to byte array?

The best possible way of conversion between byte[] and String is to ...READ MORE

answered Aug 22 in Java by Sirajul
• 25,420 points
62 views