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
2,865 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,840 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
1 answer

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

private final static char[] hexarr = "0123456789ABCDEF".toCharArray(); public ...READ MORE

answered May 24, 2018 in Java by sharth
• 3,320 points
290 views
0 votes
1 answer

How to convert a java string into byte array

You can probably use ByteBuffer:  byte[] byte = ...READ MORE

answered Jun 21, 2018 in Java by Perry
• 17,010 points
37 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
123 views
0 votes
1 answer

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

you want to use the Arrays.toString(int[]) method: import java.util.Arrays; int[] array ...READ MORE

answered Jun 7, 2018 in Java by Akrati
• 3,150 points
161 views
0 votes
1 answer

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

You can convert a String to int by using a function: int ...READ MORE

answered Apr 12, 2018 in Java by sharth
• 3,320 points
85 views
0 votes
1 answer

How can I convert an 'ArrayList<String> to 'String[]' in Java

List<String> list = new ArrayList<String>(); String[] array = ...READ MORE

answered Apr 20, 2018 in Java by Daisy
• 8,040 points
116 views
0 votes
1 answer

How do I convert an input stream into a byte array

There is a simple solution without the ...READ MORE

answered Apr 25, 2018 in Java by developer_1
• 3,280 points
201 views
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
50 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
49 views
0 votes
1 answer

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

The conversion between byte[] and String is to explicitly state the ...READ MORE

answered May 14, 2018 in Java by parth295
• 4,600 points
38 views