Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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+

share|improve this question
    
Can I clarify if Read message +[B@161cd475+ is valid for the String 'input' or not? –  Alvin Bunk Oct 26 '14 at 3:24
    
@AlvinBunk Yes, "[B@161cd475" is the text needed. –  The Hiary Oct 26 '14 at 3:32

2 Answers 2

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.

share|improve this answer
    
I got a compilation error "byte cannot be dereferenced" –  The Hiary Oct 26 '14 at 3:55

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 + "+");
share|improve this answer
    
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. –  The Hiary Oct 26 '14 at 19:49
    
Maybe do you mean you should be storing as a char[] array. Since storing as byte[] will store as numbers... (decimal specifically). –  Alvin Bunk Oct 26 '14 at 23:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.