Results 1 to 2 of 2
  1. #1
    YellowSun is offline Member
    Join Date
    Jan 2012
    Rep Power

    Default String to byte conversion


    I'm using the following code to encrypt a String (inText) whose output is a byte array named cipherText;

    Java Code:
    byte[] cipherText;
    The cipherText is printed in a textbox as follows:

    Java Code:
    encText.setText(new String(cipherText));
    Everything works fine until here. However, in the decryption section, I need to get the contents of the textbox as a byte array again. For this purpose, I use the following code:

    Java Code:
    byte[] cText;
    When I try to do the encryption it gives a 'bad size' error. I found out that the lenghts of the two byte arrays cipherText and cText aren't equal:

    Java Code:
        		boolean res=Arrays.equals(cText, cipherText);
    The 'result' textbox always prints 'false' meaning that the two byte arrays cipherText and cText aren't equal. However I convert cipherText to a String to print in a textbox and then read the contents of that textbox, convert to String back and then to Byte Aray again. Obviously some data is lost during these conversions. What would you recommend to solve this problem?

    Last edited by YellowSun; 02-02-2012 at 07:45 PM.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Eastern Florida
    Rep Power

    Default Re: String to byte conversion

    I found out that the lenghts of the two byte arrays cipherText and cText aren't equal:
    Print them both out to see what the difference is. The Arrays toString() method can format arrays.
    If you have non-text values you will need to write a loop and use the Integer.toHexString() method to show the contents of the bytes

    If the bytes can contain non-text characters the conversion to String is not symmetric. Several different byte patterns will generate the same character: a '?'

    The String class has a constructor that will take a Charset with better encoding/decoding characteristics. To find which one works, fill a byte array with values from 0 to 255, convert to String and then back to an array and compare the input array with the output array to see if all the bytes make it without loss.

Similar Threads

  1. Replies: 2
    Last Post: 11-21-2011, 12:08 AM
  2. String to Hex Conversion
    By mocha in forum New To Java
    Replies: 0
    Last Post: 03-17-2010, 08:45 AM
  3. image to byte code file conversion
    By nupurashi in forum New To Java
    Replies: 0
    Last Post: 01-28-2009, 10:25 AM
  4. String Conversion....
    By hotice1027 in forum New To Java
    Replies: 8
    Last Post: 11-28-2008, 10:52 PM
  5. string conversion??
    By j2vdk in forum New To Java
    Replies: 13
    Last Post: 09-19-2008, 03:35 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts