Byte[ ]    and    String

I am reading data into a byte array which i declare to be of size (lets say 40). the data that i read varies between lets say 30-40(but i still delare the byte array to be of size 40 so that it has enough space to handle cases from 30-40). The problem is that I need to create a string with this data...and i do so using
String data = new String (byteArray[);               //where byteArray holds data that i read
but for some reason when i try to print data...it prints the character [][][][]][][] for the unused portion of the byte array.
for example if my data is 123456789......................30.
and i read it into a byte array of size 40
and then convert to string and try to print it wil print 123456789................30[][][][][][][][][] .
how can i solve this problem?

heres some code of what im trying to do, if you dont understand datagrams you can just ignore those specifis
public String recieveCommand(){
byte[] data = new byte[40];
try{
packet=new DatagramPacket(data,40);
socket.receive(packet);
}catch(Exception e){System.out.println(e.toString());}
String command=new String( packet.getData() );

Similar Messages

  • Conversion of byte into string

    how can we convert byte into string???
    would u plzz help me??

    It depends on what relationship you want between byte and string. Is the string the numeric representation or the character value?
    byte b = (byte)65;
    String s1 = String.valueOf(byte); // gives "65"
    String s2 = new String(new byte[]{b}, "ISO-8859-1");  // gives "A"

  • Conversion of String to Bytes and Length Calculation

    hi,
    How can I convert
    String to Bytes
    Bytes to String
    int to Bytes
    Bytes to int
    & int to String
    And I have to calculate the Length in Bytes of a String and int.
    Thanks

    double d = Double.parseDouble(new String(byteDouble)); Java doesn't seem to accept to convert byteDouble to a String...
    Exception in thread "main" java.lang.NumberFormatException: For input string: "[B@1d9fd51"
      at java.lang.NumberFormatException.forInputString (NumberFormatException.java:48)
      at java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1213)

  • Byte to String conversion for encryption and decryption

    Hi Friends ,
    I am trying to encrypt a password string and then decrypt it .
    The thing is i need to convert the encrypted String which is a byte array to a string . While decrypting i need to convert the encrypted string to a Byte .
    I tried using String.getBytes() for converting a string to byte array , but this is giving an exception
    javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipherPlease find below my code
    import java.security.Key;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import sun.misc.BASE64Encoder;
    import sun.misc.BASE64Decoder;
    * @author rajeshreddy
    public class Encrypt
        public static void main(String[] args)
            try
            BASE64Encoder en = new BASE64Encoder();
            BASE64Decoder en1 = new BASE64Decoder();
                String password = "S_@!et";
                KeyGenerator kg = KeyGenerator.getInstance("DESede");
                Key key = kg.generateKey();
                Cipher cipher = Cipher.getInstance("DESede");
                cipher.init(Cipher.ENCRYPT_MODE, key);
                // Encrypt password
                byte[] encrypted = cipher.doFinal(password.getBytes());
                String e = new String(encrypted);
                byte[] toDecrypt  = e.getBytes();
                // Create decryption cipher
                cipher.init(Cipher.DECRYPT_MODE, key);
                byte[] decrypted = cipher.doFinal(toDecrypt);
                // Convert byte[] to String
                String decryptedString = new String(decrypted);
                System.out.println("password: " + password);
                System.out.println("encrypted: " + encrypted);
                System.out.println("decrypted: " + decryptedString);
            } catch (Exception ex)
                ex.printStackTrace();
    }I cab use sun.misc.BASE64Decoder and sun.misc.BASE64Encoder which avoids this error, but this packages are sun proprietery packages so there is a chance of removing these in future releases.
    Please suggest me the best way to tackle this

    1) The "Jakarta Commons Codec" project has Base64 and Hex encoders that are well tested and well regarded. Google is your friend.
    2) Since this is a new project, you should use AES rather than DESede.
    3) The defaults when generating the Cipher object using
    Cipher cipher = Cipher.getInstance("DESede");
                is for ECB block mode with PKCS5 padding. ECB is not a good block mode since it allows some limited forgery though splicing of ciphertext. Use one of the feedback modes such as CBC.
    4) Why are you encrypting passwords rather than just hashing them? While there are situations where encryption rather than hashing is required, it is not the norm and does normally require justification.
    5) Converting encrypted or hashed data to a String is not normally required. What are you doing with that requires this?
    Edited by: sabre150 on Dec 29, 2008 7:44 AM

  • Trying to understand the details of converting an int to a byte[] and back

    I found the following code to convert ints into bytes and wanted to understand it better:
    public static final byte[] intToByteArray(int value) {
    return new byte[]{
    (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff) };
    }I understand that an int requires 4 bytes and that each byte allows for a power of 8. But, sadly, I can't figure out how to directly translate the code above? Can someone recommend a site that explains the following:
    1. >>> and >>
    2. Oxff.
    3. Masks vs. casts.
    thanks so much.

    By the way, people often introduce this redundancy (as in your example above):
    (byte)(i >> 8 & 0xFF)When this suffices:
    (byte)(i >> 8)Since by [JLS 5.1.3|http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#25363] :
    A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T.Casting to a byte is merely keeping only the lower order 8 bits, and (anything & 0xFF) is simply clearing all but the lower order 8 bits. So it's redundant. Or I could just show you the more simple proof: try absolutely every value of int as an input and see if they ever differ:
       public static void main(String[] args) {
          for ( int i = Integer.MIN_VALUE;; i++ ) {
             if ( i % 100000000 == 0 ) {
                //report progress
                System.out.println("i=" + i);
             if ( (byte)(i >> 8 & 0xff) != (byte)(i >> 8) ) {
                System.out.println("ANOMOLY: " + i);
             if ( i == Integer.MAX_VALUE ) {
                break;
       }Needless to say, they don't ever differ. Where masking does matter is when you're widening (say from a byte to an int):
       public static void main(String[] args) {
          byte b = -1;
          int i = b;
          int j = b & 0xFF;
          System.out.println("i: " + i + " j: " + j);
       }That's because bytes are signed, and when you widen a signed negative integer to a wider integer, you get 1s in the higher bits, not 0s due to sign-extension. See [http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2]
    Edited by: endasil on 3-Dec-2009 4:53 PM

  • ByteArray to String and String to ByteArray  error at readUTF from datainpu

    hi everybody this is my first post I hope I can find the help I need I have been doing some research and couldnt find the solution thanks in advanced
    The Objective:
    im building a client server application with java and I need to send a response from the server to the client via Socket
    so the response is like this : <Signal : ByteArray> where Signal is a String so the client can Identify the Type of response
    and the ByteArray is an Array of bytes containing the Information I need
    The Problem:
    I have an Array of bytes containing the info to send and I need to pass this byte[] to a String add some String that let me Identify the data in the client side then remove the identifier in the client side and convert the resulting String back to an array of bytes this doesnt work
    The Code:
    Server Side (Creating the Byte Array):
    public byte[] createData(){
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    DataOutputStream dos = new DataOutputStream(baos);               
                    dos.writeUTF(requestedFile.getName());
                    dos.flush();
                    byte[] data = baos.toByteArray();
                    return data;
    }Server Side (Converting the byte[] to String and Add some Identifier)
    byte[] data= createData(); //Obtain the data  in a byte[]
    String response = new String(data);  //Convert the Data to String
    String Identifier= "14"; // to identify in the client side the data received this will be removed later
    response = Identifier+response;  // add the identifier to the String
    sendToClient( response.getBytes() );  //obtain bytes from the complete Response and send them to clientClient Side ( Receive the response that is a byte array containing the identifier plus the info <Identifier : info> )
                int index=response.indexOf(":")+1;  //find the index of the : so i can delete the identifier
                response=response.substring(index); // delete the identifier
                byte[] data = response.getBytes(); // obtains the bytes for the info ONLY cause the string no longer has identif
                receiveData ( data ); // send the data to be read by this method Client Side (Receive the Info sent from the server and read it)
                public void receiveData ( byte[] data ) {
                   ByteArrayInputStream bais = new ByteArrayInputStream ( data );
                   DataInputStream dis= new DataInputStream ( bais );
                   setTotalSize ( dis.readUTF( ) ); // here is the error  it catches an EndOfFileException without read the info
                }im tried sending other values like long and int and i was able to read them but the problem is with the Strings at the ReadUTF()
    Im tried to be the most clear as possible please help me this is driving me nuts
    and I would really appreciatte all your comments thanks

    lemaniak wrote:
    The Objective:
    im building a client server application with java and I need to send a response from the server to the client via Socket
    so the response is like this : <Signal : ByteArray> where Signal is a String so the client can Identify the Type of response
    and the ByteArray is an Array of bytes containing the Information I need
    The Problem:
    I have an Array of bytes containing the info to send and I need to pass this byte[] to a String add some String that let me Identify the data in the client side then remove the identifier in the client side and convert the resulting String back to an array of bytes this doesnt workFirst of all, well done: a nicely explained problem. I wish more people were as clear as you.
    Second: I'm no expert on this stuff, so I may well be wrong, but I did note the following:
    1. I can't see anywhere where you're putting out the ":" to separate your signal.
    2. You seem to be doing an awful lot of conversions from Strings to bytes and vice-versa, but only your filename is specified as a UTF-8 conversion. Could you not do something like:
    dos.writeUTF("14:" + requestedFile.getName());or indeed, more generically
    dos.writeUTF(signal + ":" + messageBody);from inside a createMessage() method.
    3. You haven't included the sendToClient() code, but your createData() looks suspiciously like what I would put in a method like that.
    From what I understand, you usually want mirror-images of your streams at your sending and receiving ends, so if your client is expecting an DataInputStream wrapping a ByteArrayInputStream to be read via readUTF(), your server better be sending a ByteArrayOutputStream wrapped in a DataOutputStream created, in its entirety, by writeUTF().
    But after your UTF conversion, you're adding your signal and then using String.getBytes(), which uses the default character set, not UTF.
    HIH (and hope I'm right :-))
    Winston

  • I pull fiftyfour bytes of data from MicroProcessor's EEPROM using serial port. It works fine. I then send a request for 512 bytes and my "read" goes into loop condition, no bytes are delivered and system is lost

    I pull fiftyfour bytes of data from MicroProcessor's EEPROM using serial port. It works fine. I then send a request for 512 bytes and my "read" goes into loop condition, no bytes are delivered and system is lost

    Hello,
    You mention that you send a string to the microprocessor that tells it how many bytes to send. Instead of requesting 512 bytes, try reading 10 times and only requesting about 50 bytes at a time.
    If that doesn�t help, try directly communicating with your microprocessor through HyperTerminal. If you are not on a Windows system, please let me know. Also, if you are using an NI serial board instead of your computer�s serial port, let me know.
    In Windows XP, go to Start, Programs, Accessories, Communications, and select HyperTerminal.
    Enter a name for the connection and click OK.
    In the next pop-up dialog, choose the COM port you are using to communicate with your device and click OK.
    In the final pop
    -up dialog, set the communication settings for communicating with your device.
    Type the same commands you sent through LabVIEW and observe if you can receive the first 54 bytes you mention. Also observe if data is returned from your 512 byte request or if HyperTerminal just waits.
    If you do not receive the 512 byte request through HyperTerminal, your microprocessor is unable to communicate with your computer at a low level. LabVIEW uses the same Windows DLLs as HyperTerminal for serial communication. Double check the instrument user manual for any additional information that may be necessary to communicate.
    Please let me know the results from the above test in HyperTerminal. We can then proceed from there.
    Grant M.
    National Instruments

  • Problems converting byte[] to string

    I use
    byte[] encryptedBytes = cipher.doFinal(bytesToEncrypt);
    String Ciphertext = new String(encryptedBytes);
    and sometimes i get the correct answer ans sometimes no. If yo want the code is in this post:
    http://forum.java.sun.com/thread.jspa?threadID=790137&start=15&tstart=0

    That's because the C language lacks true character and string data types. It only has arrays of bytes. Unfortunately in C bytes are misleadingly called "chars."
    It works if you put ASCII because byte sequences that correspond to ASCII characters can, on most systems, be safely converted to characters and strings. You see, conversions from bytes to characters are done using things called "encoding schemes" or just encodings. If you don't specify an encoding, the system's default is used. The default encoding can be pretty much anything so it's best not to assume much about it.
    You can also use a fixed encoding, like this:String Ciphertext = new String(encryptedBytes, "ISO-8859-1");Just remember that when you convert the string back to bytes you have to use the same encoding again, that isbyte[] cipherBytes = cipherString.getBytes("ISO-8859-1");

  • Encoded double byte characters string conversion

    I have double byte encoded strings stored in a properties file. A sample of such string below (I think it is japanese):
    \u30fc\u30af\u306e\u30a2
    I am supposed to read it from file, convert it to actual string and use them on UI. I am not able to figure how to do the conversion -- the string contains text as is, char backslash, char u, and so on. How to convert it to correct text (either using ai::UnicodeString or otherwise)?
    Thanks.

    Where did this file come from? Some kind of Java or Ruby export? I don't think AI has anything in its SDK that would natively read that. You could just parse the string, looking for \u[4 characters]. I believe if you created a QChar and initialized it with the integer value of the four-character hex string, it would properly create the character.

  • Object to byte [] and byte [] to Object

    Hi,
    I am quite new to java and need some help. My question is how can I convert an Object to byte [] and convert back from byte [] to Object.
    I was thinking of something like:
    From object to byte []
    byte [] object_byte=object.toString().getBytes();
    When I try to do:
    String obj_string=object_byte.toString();
    But obj_string is not even equal to object.toString().
    Any suggestions?
    Thanks

    // byte[] to Object
    byte[] b = new byte[]{1};
    Object o = (new ObjectInputStream(new ByteArrayInputStream(b))).readObject();
    // Object to byte[]
    Object o = new Object();
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();    
    ObjectOutputStream objStream = new ObjectOutputStream(byteStream);       
    objStream.writeObject(o);  
    byte[] b = byteStream.toByteArray();

  • How to convert byte into string

    can any tell me how to convert byte into string
    when im an debugging thid code in eclipse it shows the result in integer format instead of string but in command prompt it is showing result in string format..........plz help
    package str;
    import java.io.*;
    public class Testfile {
    public static void main(String rags[])
    byte b[]=new byte[100];
    try{
    FileInputStream file=new FileInputStream("abc.txt");
    file.read(b,0,50);
    catch(Exception e)
         System.out.println("Exception is:"+e);
    System.out.println(b);
    String str=new String(b);
    System.out.println(str);
    }

    Namrata.Kakkar wrote:
    errors: count cannot be resolved and Unhandled exception type Unsupported Encoding Exception.
    If i write an integer value instead of "count" then Unhandled exception type Unsupported Encoding Exception error is left.This is elementary. You need to go back to [http://java.sun.com/docs/books/tutorial/|http://java.sun.com/docs/books/tutorial/] .

  • Compare string and string from db

    I successfully queried a field from mysql into a jcombobox.
    What I can't figure out is why:
    String fromDB = comboBox.getSelectedItem().trim();
    AND
    String newString = "sameStringFromMySQL";are not equal. I already trimmed the text from the combo box but they are still not considered equal.
    WHY???

    just like how i described above.
    (fromDB.equals(newString)) returns false.
    Then they are not equal.
    Most likely reasons:
    -fromDB: This is starting with the text you think.
    -fromDB: You aren't getting it from the right place.
    -fromDB: You are modifying it before it gets to the comparison.
    -NewString: Doesn't have the value you think.
    -The comparison above isn't really the problem.
    You can always print the bytes in any string by using the getBytes() method on String and printing out both strings just before the above comparison (not elsewhere.)

  • Byte and char !!!

    Hi!
    What is the diference between an byte and char in Java! Could I use char instead of byte and reverse?
    Thanks.

    TYPE BYTE BITS SIGN RANGE
    byte 1 8 SIGNED -128 to 127
    char 2 16 UNSIGNED \u0000 to \uFFFF
    Both the date types can be interchanged
    Have a look at this
    class UText
         public static void main(String[] args)
              byte c1;          
              char c2= 'a';
              c1 = (byte) c2;
              c2 = (char) c1;          
              System.out.println(c1 +" "+c2);
    But It Leads to confusion while interchanging because of its SIGN. And the range of byte is very less.So its better to prefer char.

  • How to Plot number and string in one row (data logger counter) ?

    hi all i made data log quantity using Digital Counter via modbus to monitoring quantity and reject that has and Name Operator, Machine and Part Number.
    i have problem about plot the number & string in one row, as shown on the picture below :
    how to move that string on one row ? i attach my vi.
    Thanks~
    Attachments:
    MODBUS LIB Counter.vi ‏39 KB

    Duplicate and answered - http://forums.ni.com/t5/LabVIEW/How-to-Plot-number-and-string-in-one-row-data-logger-counter-via/m-p...

  • Difference between String=""; and String =null

    I want to know the difference especially the ADVANTAGE between the following-
    1. String s="";
    String s="ABC"
    and
    String s;
    String s="ABC";
    or String s=null;
    String s="ABC";
    2. Object anyObject;
    anyObject-new Object();
    and
    Object anyObject=null;
    anyObject=new Object();

    Tanvir007 wrote:
    I want to know the difference especially the ADVANTAGE between the following-
    1. String s="";s points to the empty string--the String object containing no characters.
    String s="ABC"s points to the String object containing the characters "ABC"
    String s; Declares String reference varialbe s. Doesn't not assign it any value. If it's a local variable, it won't have a value until you explicitly assign it. If it's a member variable, it will be given the value null when the enclosing object is created.
    String s="ABC";Already covered above.
    or String s=null;s does not point to any object.
    String s="ABC";???
    You've already asked this twice.
    Are you talking about doing
    String s = null;
    String s = "ABC";right after each other?
    You can't do that. You can only declare a variable once.
    If you mean
    String s = null;
    s = "ABC";It just does what I described above, one after the other.
    2. Object anyObject;
    anyObject-new Object();
    and
    Object anyObject=null;
    anyObject=new Object();As above: In the first case, its value is undefined until the new Object line if it's a local, or it's null if it's a member.
    As for which is better, it depends what you're doing.

Maybe you are looking for

  • LSMW Upload vendor master data

    I am uploading vendor master data via a batch input in LSMW (program RFBIKR00). I uploaded all the vendors for 1 company code. When I try to upload the vendors for another company code, in the step “Create Batch Input Session” I get the error: “Trans

  • Error in MSS Internal Service request

    I install MSS 60.1.5 under EP 60 sp10. All iviews under My budget (internal service request) are not working now, such as "change internal order request", "change project" and so on. After clicking the "submit" button, the error shows "<b>An error oc

  • WORKFLOW PROCESS IS NOT WAITING FOR USER INPUT LIKE RE-ASSIGN FUNCTION

    I am using Stand alone Workflow 2.6, In my workflow process which is an Issue tracking system which is working fine. On Enhancement I would like to create my own RE-ASSIGN function which will, Change the ownership of an issue totally to other user. F

  • Weblogic Admin Server Crash while accessing sbconsole dashboard

    I'm having this issue where the Admin Server crash when I try to access sbconsole Dashboard page. There is no exception or strack trace before it crash, it just crash and admin server got restarted. I've noticed error stack trace for the below when a

  • Macbook (MB403LL/A) its good?

    Its good this macbook to use autocad, civl & civil 3d, The video card is enough to use civil 3d and make renders or im going to have pproblems I hope someone with experience with these programs in macbook answers. Thanks I need to know because i want