Results 1 to 19 of 19
Like Tree1Likes
  • 1 Post By Tolls

Thread: Byte [] to String

  1. #1
    taptaptill is offline Member
    Join Date
    Dec 2012
    Posts
    32
    Rep Power
    0

    Default Byte [] to String

    Hello Everyone,
    Well obviously I have a problem :
    I'm reading bytes coming from a serial port and I want to show these bytes like strings well it does show but there's some letter that 're incomprehensible.
    This is my code :
    Java Code:
      byte [] readbuffer = new byte [20];
                                try {
                                    while (inputstream.available () > 0 )
                                    {
                                        int nymBytes = inputstream.read(readbuffer);
                                    }
                                    
                                   String tr = new String (readbuffer,"US-ASCII");
                                    System.out.println(tr);
    So is there another way around ? and thanks .

  2. #2
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Location
    Bali, Indonesia
    Posts
    758
    Rep Power
    8

    Default Re: Byte [] to String

    What is the result that you expect from the code and what you get at the moment?

    In your snippet you are likely to print out the last data in the buffer.
    Last edited by wsaryada; 12-19-2012 at 11:27 AM.

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default Re: Byte [] to String

    Don't use the available() method.
    Use:
    Java Code:
    int numBytes = 0;
    while ((numBytes = inputStream.read(readbuffer)) > -1) {
    }
    since read(buffer) returns the number of bytes read, and -1 means EOS.
    Also, as wsaryada suggests, your current code only does the last 20 (or less) bytes.
    You want to outputting as you loop.
    Note, you want to only output the number of bytes read...anything more is just going to be garbage.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  4. #4
    taptaptill is offline Member
    Join Date
    Dec 2012
    Posts
    32
    Rep Power
    0

    Default Re: Byte [] to String

    thanks for the quick response.
    What I expect is showing the traffic coming from the serial port and I know that 're letters & numbers.
    what's sent it's showed but with uncomprehensible letters (small rectangles).

  5. #5
    taptaptill is offline Member
    Join Date
    Dec 2012
    Posts
    32
    Rep Power
    0

    Default Re: Byte [] to String

    so I changed it like u said :
    Java Code:
    int numBytes;
                                
                                byte [] readbuffer = new byte [20];
                               
                                try {
                                     String tr = new String (readbuffer,"US-ASCII");
                                    while ((numBytes = inputstream.read(readbuffer))  > -1 )
                                    {
                                         tr =readbuffer.toString();
                                         System.out.println(tr);
                                         TrafficSerialPort.Traffic.setText(tr);
                                    }
                                    }catch (IOException e) {System.out.println(e);}
    what I get is : [B@1296d1d
    But I want actual words!

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default Re: Byte [] to String

    First, you need to use the String constructor that takes an offset and length, as well as the buffer and charset.
    That's because you will not always have 20 bytes used in your buffer.
    The numBytes variable is very important.

    Second you need to do this inside the loop.
    At the moment you are doing the conversion outside the loop, and with an empty buffer.
    Your:
    Java Code:
    tr = readbuffer.toString();
    is simply using the default Object toString, which is the memory address of the object in question.
    It is not doing any sort of translation of the byte[].

    Finally, do you really want to be updating the Traffic field everytime around this loop?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    taptaptill is offline Member
    Join Date
    Dec 2012
    Posts
    32
    Rep Power
    0

    Default Re: Byte [] to String

    Ok now I'm back to start point : this is my code now :
    Java Code:
    int numBytes;
                                
                                byte [] readbuffer = new byte [20];
                               
                                try {
                                     
                                    while ((numBytes = inputstream.read(readbuffer))  > -1 )
                                    {
                                        String tr = new String (readbuffer,"US-ASCII");
                                         
                                         System.out.println(tr);
                                         TrafficSerialPort.Traffic.append(tr);
                                    }
                                     }catch (IOException e) {System.out.println(e);}
    Now it shows me the Traffic with letters & all but with some garbage (small rectangles) and that's what I want to dispose off.
    yes cause the traffic is always active & changing so I need to capture the Traffic and show it.

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default Re: Byte [] to String

    To quote myself:
    "use the String constructor that takes an offset and length"

    You are assuming your buffer is filled each time.
    This is not necessarily the case.

    And if, when that is sorted, you still get "garbage" then you need to check whether the data you are receiving is actually in US-ASCII.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  9. #9
    Sierra is offline AN21XX
    Join Date
    Mar 2012
    Location
    Munich
    Posts
    297
    Rep Power
    3

    Default Re: Byte [] to String

    You will not succeed reading from a stream that way. As long as the stream is open there might be more input, so you need to append the input to another buffer and decide at whcih point you want to show your content to the user. While using println() will succeed as it is also a stream most other uses will not.
    When you have your buffer filled you may split that content up according to your serial separation characters/synchronization bytes, etc. You should make yourself familiar with serial communication in that respect.

    In general: It is not a good idea to say that "with letters & all but with some garbage" is a problem, but to show the example. E.g. the [B@1296d1d is a direct result from your wrong usage of toString and not from the serial port. So try to keep your description with as much useful information as possible.
    I like likes!

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default Re: Byte [] to String

    I assumed the append() call on whatever Traffic is is where they'r ebuilding up the response?
    Have I missed something here?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  11. #11
    Sierra is offline AN21XX
    Join Date
    Mar 2012
    Location
    Munich
    Posts
    297
    Rep Power
    3

    Default Re: Byte [] to String

    I think you are right, I was still with the first two versions he presented in this and the other thread I guess... maybe I am getting too old... ^^
    However he will have to go through his input byte by byte that way to eliminate unwanted characters... or use RegEx...?
    Last edited by Sierra; 12-19-2012 at 03:04 PM.
    I like likes!

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default Re: Byte [] to String

    Well, at the moment they're not writing the buffer correctly anyway.
    And I wouldn't be surprised to find out that it is not a US-ASCII stream coming in.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  13. #13
    taptaptill is offline Member
    Join Date
    Dec 2012
    Posts
    32
    Rep Power
    0

    Default Re: Byte [] to String

    well this is how I handle the events on the serial port so I can read the traffic(Actually my traffic is a telnet traffic over serial port and i'm using a computer on the other end to send text to this one (just to try my program) ) :
    Java Code:
    public void serialEvent(SerialPortEvent event) {
    		//gestion des événements sur le port :
    		//on ne fait rien sauf quand les données sont disponibles
    		switch (event.getEventType()) {
    			case SerialPortEvent.BI :
    			case SerialPortEvent.OE :
    			case SerialPortEvent.FE :
    			case SerialPortEvent.PE :
    			case SerialPortEvent.CD :
    			case SerialPortEvent.CTS :
    			case SerialPortEvent.DSR :
    			case SerialPortEvent.RI :
    			case SerialPortEvent.OUTPUT_BUFFER_EMPTY :
    				break;
    			case SerialPortEvent.DATA_AVAILABLE :
                                int numBytes;
                                
                                byte [] readbuffer = new byte [20];
                               
                                try {
                                     
                                    while ((numBytes = inputstream.read(readbuffer))  > -1 )
                                    {
                                        String tr = new String (readbuffer);
                                         
                                         System.out.println(tr);
                                         TrafficSerialPort.Traffic.append(stripGarbage(tr));
                                    }
                                  
                                }catch (IOException e) {System.out.println(e);}
                                  break;
                       }
    	}
    Code stripGarbage (); :
    Java Code:
    private String stripGarbage(String s) {
        StringBuilder sb = new StringBuilder(s.length());
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if ((c >= 'A' && c <= 'Z') || 
                (c >= 'a' && c <= 'z') ||
                (c >= '0' && c <= '9')) {
                sb.append(c);
            }
        }
        return sb.toString();
    }
    is this the way the best way?
    and the other thing is : when I'm reading the traffic some of words came unfinished. this is a portion from the result : Hello...123...Hello...123..3llo.Hello...123
    and thanks a lot for the responses.

  14. #14
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default Re: Byte [] to String

    You're still assuming the whole buffer is being populated.
    Until you actually fix that problem you will continue to get incorrect output.

    I have said this several times now, and am beginning to get bored of it...
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  15. #15
    taptaptill is offline Member
    Join Date
    Dec 2012
    Posts
    32
    Rep Power
    0

    Default Re: Byte [] to String

    ok i'll try and get back to you thanks and sorry for the inconvinience.

  16. #16
    taptaptill is offline Member
    Join Date
    Dec 2012
    Posts
    32
    Rep Power
    0

    Default Re: Byte [] to String

    So here's my solution to this problem : now I wait for the buffer to be filled then I read it.well this solution works for me but it's too slow
    Java Code:
    int numBytes;
                                
                                byte [] readbuffer = new byte [20];
                               try
                               {
                                try {
                                     
                                    while ((numBytes = inputstream.read(readbuffer))  > -1 )
                                    {
                                         Thread.sleep(1500);
                                         String tr =  new String(readbuffer,0,20,"ISO-8859-1");
                                         System.out.println(tr);
                                         TrafficSerialPort.Traffic.append(stripGarbage(tr));
                                    }
                                  
                                }catch (IOException e) {System.out.println(e);}
                                  } catch (InterruptedException e) {
                    System.out.println("Interrupted");   
    				
    				break;

  17. #17
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default Re: Byte [] to String

    No!
    numBytes (as I said before) is the number of bytes read into the buffer.
    Use it!
    String tr = new String(readbuffer,0,numBytes,"ISO-8859-1");

    Get rid of the thread sleep...
    Sierra likes this.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  18. #18
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,193
    Rep Power
    19

    Default Re: Byte [] to String

    You can take a horse to the water...
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  19. #19
    taptaptill is offline Member
    Join Date
    Dec 2012
    Posts
    32
    Rep Power
    0

    Default Re: Byte [] to String

    Lol thanks
    it works now & i need to do much more effort but thanks to you and untill next time .

Similar Threads

  1. Byte encapsulation in String
    By ozpenstillson in forum Advanced Java
    Replies: 4
    Last Post: 06-29-2012, 06:42 PM
  2. Replies: 2
    Last Post: 11-21-2011, 12:08 AM
  3. Expressing a byte string
    By DeptOfMeteors in forum New To Java
    Replies: 14
    Last Post: 11-25-2010, 10:47 PM
  4. String from byte array
    By justint in forum New To Java
    Replies: 2
    Last Post: 01-22-2010, 06:58 AM
  5. String byte storage
    By bozovilla in forum New To Java
    Replies: 1
    Last Post: 11-24-2007, 06:35 AM

Posting Permissions

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