0

I have a client server Java code and the client is reading in a string "input" and it should then decrypt it, the decryption function needs an array of bytes, so I need to convert the string to array of bytes, which is done using "getBytes()" function, however it seems that this function is modifying the String! How can I convert the string into an array of bytes without changing its content.

   String input = inputline.substring(66, inputline.length());
   System.out.println("Read message +"+input+"+");
   byte[] bx = input.getBytes(Charset.forName("UTF-8"));
   System.out.println("Read message +"+bx.toString()+"+");
   System.out.println("Read message +"+bx+"+");

the output of the code snippet is as follows:

Read message +[B@161cd475+

Read message +[B@4e25154f+

Read message +[B@4e25154f+

2
  • Can I clarify if Read message +[B@161cd475+ is valid for the String 'input' or not? Commented Oct 26, 2014 at 3:24
  • @AlvinBunk Yes, "[B@161cd475" is the text needed. Commented Oct 26, 2014 at 3:32

2 Answers 2

1

Try writing a for loop to print out the results. I believe Java is spitting out a random memory value for your output.

(int i = 0; s <= bx.length;i++)
{
 System.out.println("Read message +" + bx[i].toString() + "+");
 System.out.println("Read message +" + bx + "+");
}

Not sure if my for loop is correct, but it may give you something to work with. I hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

I got a compilation error "byte cannot be dereferenced"
0

This should work for you. I needed to make a String object from the byte array...

String inputline = "[B@161cd475";
String input = inputline.substring(0, inputline.length());
System.out.println("Read message +"+input+"+");
byte[] bx = input.getBytes();

// Convert to String object
String tmp = new String(bx);
// Print statements.
System.out.println("Read message +" + tmp + "+");

2 Comments

Thank you, your code outputs the correct output, but I need the byte array "bx" to contain the same values as the String "[B@161cd475" currently it contains "[B@4e25154f" which is not what I want.
Maybe do you mean you should be storing as a char[] array. Since storing as byte[] will store as numbers... (decimal specifically).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.