How do I convert byte[] to String?

I've got a class that pulls information from a GPS receiver on a COM port. That works fine, but the information I'm getting from the port is in the following format:
Reading serial port...
44,44,52,46,50,44,77,44,45,51,52,46,50,44,77,44,44,48,48,48,48,42,120,30,-104,-128,96,120,96,0,-26,126,-98,-104,-98,0,30,-122,6,30,-122,6,120,-122,-32,-122,-32,-122,-32,-122,-32,-122,-32,-122,-32,-122,-32,-122,-32,-122,-32,-122,-32,120,-122,-32,-122,-32,-122,-32,-122,-104,-122,6,120,6,-98,30,-104,-128,96,120,96,0,-26,24,-26,-26,-104,30,30,-122,24,120,-32,120,30,102,120,-26,120,-26,-4,48,50,52,44,86,44,52,48,53,54,46,49,50,50,49,44,78,44,48,55,51,53,52,38,54,70,70,-58,118,-115,25,25,89,70,6,102,6,-122,-58,-58,-58,-26,83,102,-122,
-61,-31,
36,71,80,71,71,65,44,50,49,52,53,53,54,46,48,50,52,44,52,48,53,54,46,49,50,50,49,44,78,44,48,55,51,53,52,46,50,51,52,52,44,87,44,48,44,48,48,44,44,52,46,50,44,77,44,45,51,52,46,50,44,77,44,44,48,48,48,48,42,52,66,13,10,36,71,80,71,83,
65,So it's pretty obvious that it's spitting out ASCII values, so I changed the code a bit to print out the corresponding letters instead:
Reading serial port...
$GPGGA,214724.031,4056.1221,N,07354.2344,W,0,00,,4.2,M,-34.2,M,,0000*48
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
$GPGSV,3,1,11,31,70,286,,14,57,089,,32,51,293,,30,44,061,*7D
$GPGSV,3,2,11,05,24,046,,22,23,167,,20,20,315,,16,15,194,*70
$GPGSV,3,3,11,12,12,039,,29,09,103,,11,00,279,*4F
$GPRMC,214724.031,V,4056.1221,N,07354.2344,W,,,140608,,,N*68
$GPGGA,214725.031,4056.1221,N,07354.2344,W,0,00,,4.2,M,-34.2,M,,0000*49
$GPGSA,A,1,,,,,,,,,,,,,,,*1ENow those are the NMEA sentences that the GPS receiver spits out, that's exactly what I need. Only problem is I'm printing them out using the following code:
      byte[] buffer = new byte[4096];
      InputStream theInput = thePort.getInputStream();
      System.out.println("Reading serial port...");
      while (canRead()) // Loop
        int bytesRead = theInput.read(buffer);
        if (bytesRead == -1)
          break;
        for (int z = 0; z < bytesRead; z++)
             System.out.print(Character.toString((char)buffer[z]));
        }So as you can see, it's simply taking the byte, converting it from ASCII to a symbol or letter, and putting it on the screen. Then it moves onto the next byte. So what I've tried to do is change it again so that it adds each converted letter to a string value, starting a completely new string every time it hits a $ sign, which always starts a NMEA sentence:
      byte[] buffer = new byte[4096];
      InputStream theInput = thePort.getInputStream();
      System.out.println("Reading serial port...");
      while (canRead()) // Loop
        int bytesRead = theInput.read(buffer);
        if (bytesRead == -1)
          break;
        String s = "";
        for (int z = 0; z < bytesRead; z++)
             if (Character.toString((char)buffer[z]).equalsIgnoreCase("$") && s.length() > 1)
                  System.out.println(s);
                  s = Character.toString((char)buffer[z]);
             else
                  s = s + Character.toString((char)buffer[z]);
//             System.out.print(Character.toString((char)buffer[z]));
s = "";
}The problem with this is for some reason the sentences aren't whole, there's line breaks inserted into them. So when I'm passing them to the parser, I'm passing incomplete sentences. Here's the output I'm getting now:
Reading serial port...
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
.2,M,-34.2,M,,0000*4D
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
,32,51,293,,30,44,061,*7D
$GPGSV,3,3,11,12,12,039,,29,09,103,,11,00,279,*4FHow do I get each NMEA sentence into a string so I can send it to a parser? Any ideas?
Edited by: DeX on Jun 14, 2008 6:02 PM

Your problem is that you're assuming a newline actually indicates the end of a line.
Assuming you can't fix the sender (or yell at the maintainer and get him to fix it), take
advantage of the fact that you know what a valid line starts with and just ignore the newline
characters.
Thanks but that gives me the same result. I think my issue is with the multithreading,
another thread is rolling through and assigning values to the String before the previous
thread is finished copying the bytes to it. I suggest you take advantage of the StringBuilder class. Also, if you insist on using the
String(byte[ ]) constructor, you should note that you're assuming a charset, a rather
dangerous thing to do. Use the String(byte[ ], String) constructor instead and explicitly use US-ASCII.

Similar Messages

  • 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/] .

  • CS3/CS4/CS5 Win/Mac: How can I convert a Windows string to mac?

    Hi
    I have a Windows coded string. I like to convert this string into a Macintosh string. This means several characters are changed, e.g. ä, ö or ü.
    Is there a method in the Indesign SDK?
    How can I convert a windows string into a macintosh string and back?
    Thanks
    Hans

    I don't think this should work that way. If this string is in resource file, use UTF-8 encoding and make PMString do its job. use kResourceUTF8Encoded in StringTable:
    resource StringTable (kSDKDefStringsResourceID + index_enUS)
            k_enUS,                                             // Locale Id
            kResourceUTF8Encoded,                         // Character encoding converter (irp) I made this WinToMac as we have a bias to generate on Win...
                  // ----- Menu strings
                    kWFPCompanyKey,                         kWFPCompanyValue,
                    kWFPAboutMenuKey,                         kWFPPluginName "[US]...",
                    kWFPPluginsMenuKey,                    kWFPPluginName "[US]",
                        kWFPDialogMenuItemKey,               "Show dialog[US]",
                    kSDKDefAboutThisPlugInMenuKey,               kSDKDefAboutThisPlugInMenuValue_enUS,
                    // ----- Command strings
                    // ----- Window strings
                    // ----- Panel/dialog strings
                        kWFPDialogTitleKey,     kWFPPluginName "[US]",
                        kWFP_Tuna_Key,     "Tuna",
                        kWFP_Salmon_Key,     "Salmon",
                        kWFP_Bonito_Key,     "Bonito",
                        kWFP_Yellowtail_Key, "Yellowtail",
                        kWFP_Currency_Key, "$",
              // ----- Misc strings
                    kWFPAboutBoxStringKey,               kWFPPluginName " [US], version " kWFPVersion " by " kWFPAuthor "\n\n" kSDKDefCopyrightStandardValue "\n\n" kSDKDefPartnersStandardValue_enUS,
    Message was edited by: Maciej Przepióra

  • How can I convert output data (string?) from GPIB-read to an 1D array?

    Hello all,
    I am reading a displayed waveform from my Tektronix Oscilloscope (TDS3032) via the GPIB Read VI. The format of the waveform data is: positive integer data-point representation with the most significant byte transferred first (2 bytes per data point).
    The output data of GPIB-Read looks like a string(?) where the integer numbers and a sign like the euro-currency sign are seperated by spaces e.g. #5200004C3 4 4 4 4 3C3C3........ (C represents the euro-currency sign).
    How can I convert this waveform data into a 1D/2D array of real double floatingpoint numbers (DBL) so I can handle the waveform data for data-analysis?
    It would be very nice if someone know the solution for this.
    t
    hanks

    Hi,
    First of all, I'm assuming you are using LabVIEW.
    The first you need to do is parse the string returned by the instrument. In this case you need to search for the known symbols in the string (like the euro sign) and chop the string to get the numeric strings. Here are some examples on parsing from www.ni.com:
    Keyword Search: parsing
    Once you parse the numeric strings you can use the "String/number conversion VIs" in the String pallette.
    Hope this helps.
    DiegoF.Message Edited by Molly K on 02-18-2005 11:01 PM

  • How can I convert an ASCII string of variable length to a HEX number?

    Hello,
    I read data from the serial port 5 times in a second (while loop) and the number of bytes read varies every time.
    The data comes in as ASCII string, and I can see the HEX representation if I connect a HEX string indicator, but I need to permanently convert data to a HEX number. 
    How can that be done?

    Like This.
    Ton
    Free Code Capture Tool! Version 2.1.3 with comments, web-upload, back-save and snippets!
    Nederlandse LabVIEW user groep www.lvug.nl
    My LabVIEW Ideas
    LabVIEW, programming like it should be!

  • How can I convert IF_IXML_DOCUMENT to STRING?

    Hi guys,
    is it possible to  convert an XML document (type IF_IXML_DOCUMENT ) to string.
    And how to do it?
    Thanks in advace!
    Regards,
    Liying

    Hi Wang,
    You can use these function modules
    TEXT_CONVERT_XML_TO_SAP or
    SDIXML_DOM_TO_XML Convert DOM (XML) into string of bytes that can be downloaded to PC or application server
    or
    SMUM_XML_PARSE (Parse XML docment into a table structure)
    You can also refer to these:
    SMUM_XML_CREATE (Create XML document from internal table)
    SMUM_XML_CREATE_X (Create XSTRING xml doc)
    Check this code, it converts an XML data into a string internal table.
    REPORT Z_XML_TO_TABLE.
    TYPE-POOLS: ixml.
    TYPES: BEGIN OF t_xml_line,
    data(256) TYPE x,
    END OF t_xml_line.
    DATA: l_ixml TYPE REF TO if_ixml,
    l_streamfactory TYPE REF TO if_ixml_stream_factory,
    l_parser TYPE REF TO if_ixml_parser,
    l_istream TYPE REF TO if_ixml_istream,
    l_document TYPE REF TO if_ixml_document,
    l_node TYPE REF TO if_ixml_node,
    l_xmldata TYPE string.
    DATA: l_elem TYPE REF TO if_ixml_element,
    l_root_node TYPE REF TO if_ixml_node,
    l_next_node TYPE REF TO if_ixml_node,
    l_name TYPE string,
    l_iterator TYPE REF TO if_ixml_node_iterator.
    DATA: l_xml_table TYPE TABLE OF t_xml_line,
    l_xml_line TYPE t_xml_line,
    l_xml_table_size TYPE i.
    DATA: l_filename TYPE string.
    PARAMETERS: pa_file TYPE char1024 DEFAULT 'c:\temp\orders_dtd.xml'.
    Validation of XML file: Only DTD included in xml document is supported
    PARAMETERS: pa_val TYPE char1 AS CHECKBOX.
    START-OF-SELECTION.
    Creating the main iXML factory
    l_ixml = cl_ixml=>create( ).
    Creating a stream factory
    l_streamfactory = l_ixml->create_stream_factory( ).
    PERFORM get_xml_table CHANGING l_xml_table_size l_xml_table.
    wrap the table containing the file into a stream
    l_istream = l_streamfactory->create_istream_itable( table =
    l_xml_table
    size =
    l_xml_table_size ).
    Creating a document
    l_document = l_ixml->create_document( ).
    Create a Parser
    l_parser = l_ixml->create_parser( stream_factory = l_streamfactory
    istream = l_istream
    document = l_document ).
    Validate a document
    IF pa_val EQ 'X'.
    l_parser->set_validating( mode = if_ixml_parser=>co_validate ).
    ENDIF.
    Parse the stream
    IF l_parser->parse( ) NE 0.
    IF l_parser->num_errors( ) NE 0.
    DATA: parseerror TYPE REF TO if_ixml_parse_error,
    str TYPE string,
    i TYPE i,
    count TYPE i,
    index TYPE i.
    count = l_parser->num_errors( ).
    WRITE: count, ' parse errors have occured:'.
    index = 0.
    WHILE index < count.
    parseerror = l_parser->get_error( index = index ).
    i = parseerror->get_line( ).
    WRITE: 'line: ', i.
    i = parseerror->get_column( ).
    WRITE: 'column: ', i.
    str = parseerror->get_reason( ).
    WRITE: str.
    index = index + 1.
    ENDWHILE.
    ENDIF.
    ENDIF.
    Process the document
    IF l_parser->is_dom_generating( ) EQ 'X'.
    PERFORM process_dom USING l_document.
    ENDIF.
    *& Form get_xml_table
    FORM get_xml_table CHANGING l_xml_table_size TYPE i
    l_xml_table TYPE STANDARD TABLE.
    Local variable declaration
    DATA: l_len TYPE i,
    l_len2 TYPE i,
    l_tab TYPE tsfixml,
    l_content TYPE string,
    l_str1 TYPE string,
    c_conv TYPE REF TO cl_abap_conv_in_ce,
    l_itab TYPE TABLE OF string.
    l_filename = pa_file.
    upload a file from the client's workstation
    CALL METHOD cl_gui_frontend_services=>gui_upload
    EXPORTING
    filename = l_filename
    filetype = 'BIN'
    IMPORTING
    filelength = l_xml_table_size
    CHANGING
    data_tab = l_xml_table
    EXCEPTIONS
    OTHERS = 19.
    IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
    WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    ENDIF.
    Writing the XML document to the screen
    CLEAR l_str1.
    LOOP AT l_xml_table INTO l_xml_line.
    c_conv = cl_abap_conv_in_ce=>create( input = l_xml_line-data
    replacement = space ).
    c_conv->read( IMPORTING data = l_content len = l_len ).
    CONCATENATE l_str1 l_content INTO l_str1.
    ENDLOOP.
    l_str1 = l_str1+0(l_xml_table_size).
    SPLIT l_str1 AT cl_abap_char_utilities=>cr_lf INTO TABLE l_itab.
    WRITE: /.
    WRITE: /' XML File'.
    WRITE: /.
    LOOP AT l_itab INTO l_str1.
    REPLACE ALL OCCURRENCES OF cl_abap_char_utilities=>horizontal_tab
    IN
    l_str1 WITH space.
    WRITE: / l_str1.
    ENDLOOP.
    WRITE: /.
    ENDFORM. "get_xml_table
    *& Form process_dom
    FORM process_dom USING document TYPE REF TO if_ixml_document.
    DATA: node TYPE REF TO if_ixml_node,
    iterator TYPE REF TO if_ixml_node_iterator,
    nodemap TYPE REF TO if_ixml_named_node_map,
    attr TYPE REF TO if_ixml_node,
    name TYPE string,
    prefix TYPE string,
    value TYPE string,
    indent TYPE i,
    count TYPE i,
    index TYPE i.
    node ?= document.
    CHECK NOT node IS INITIAL.
    ULINE.
    WRITE: /.
    WRITE: /' DOM-TREE'.
    WRITE: /.
    IF node IS INITIAL. EXIT. ENDIF.
    create a node iterator
    iterator = node->create_iterator( ).
    get current node
    node = iterator->get_next( ).
    loop over all nodes
    WHILE NOT node IS INITIAL.
    indent = node->get_height( ) * 2.
    indent = indent + 20.
    CASE node->get_type( ).
    WHEN if_ixml_node=>co_node_element.
    element node
    name = node->get_name( ).
    nodemap = node->get_attributes( ).
    WRITE: / 'ELEMENT :'.
    WRITE: AT indent name COLOR COL_POSITIVE INVERSE.
    IF NOT nodemap IS INITIAL.
    attributes
    count = nodemap->get_length( ).
    DO count TIMES.
    index = sy-index - 1.
    attr = nodemap->get_item( index ).
    name = attr->get_name( ).
    prefix = attr->get_namespace_prefix( ).
    value = attr->get_value( ).
    WRITE: / 'ATTRIBUTE:'.
    WRITE: AT indent name COLOR COL_HEADING INVERSE, '=',
    value COLOR COL_TOTAL INVERSE.
    ENDDO.
    ENDIF.
    WHEN if_ixml_node=>co_node_text OR
    if_ixml_node=>co_node_cdata_section.
    text node
    value = node->get_value( ).
    WRITE: / 'VALUE :'.
    WRITE: AT indent value COLOR COL_GROUP INVERSE.
    ENDCASE.
    advance to next node
    node = iterator->get_next( ).
    ENDWHILE.
    ENDFORM. "process_dom
    Thanks,
    Susmitha

  • Converting byte to string

    Im doing a CRC for a txt file.
    So after the CRC calculation i got the 16bit check sum.
    How should i add the 16 bit to the file?
    The file is generated base on various objects. So it would be very good if i could convert the 16 bits into String and then add to the file as part of a text.

    Im suppose to add into the file, the 16 bits as 2 bytes of ASCII.
    Im doing this...
    int firstCRC = crc>>>8;
    int intSecCRC = 0x00ff & crc;
    String crc1 = ""+ (char)firstCRC;
    String crc2 = ""+ (char)intSecCRC;
    01000100 00111101 << CRC in binary
    firstCRC: D
    SecCRC : =
    So i will be appending 'D''and '=' into the file... is this correct?

  • Converting bytes to strings

    iam receiving data from other device iam storing hole data in byte buffer as
      byte[]  data= new byte[1024];for every read i get 16 bytes of data ..
    when iam veiwing i am getting some bytes in -ve like -127 and some or +ve 126,115. i want to convert  this data to string then how i can do this .                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Use one of the String constructors that takes a byte or byte array argument.

  • How do i convert a spreadsheet string to an array of double with out using spreadsheetstringtoarray.vi?

    Hi
    When I use spreadsheet string to array on a spreadsheet string, I get zeroes in between the numbers. The original string has a number, a tab, and another number and I want it convert to double precision format retaining the spreadsheet string format.
    How can I do this?
    Thank you.

    adrianT wrote:
    Hi
    Thanks for that.
    But your method produces just one column of data. I need two.
    Thank you.
    When I use the vi on the data you provided, I get two columns. You can see that by yourself on the attached vi, where I have saved the calculated results as default values (there is an additionnal modification to read directly a file). Are you making tests on different sets of data ? Could you give me an example of what's returned by my vi. Or are you using a modified version of my vi ? In this last case, could you post it ?
    CC
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        
    Attachments:
    Clean text 3.vi ‏45 KB

  • 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");

  • How can I Convert a numeric string to a formatted string?

    I have a string value returned from a background tool that will range from 0 to possibly terabytes as a full number.  I want to format that number to use commas and to reduce the character count using an appropriate size modifier (KiB, MiB, GiB, etc).  I've tried converting the string number to a Double value using Double.parseDouble() and then performing the math based on the size of the value with this code:
    Double dblConversionSize;
    String stCinvertedSize;
    dblConversionSize = Double.parseDouble(theValue);
    if (dblConversionSize > (1024 * 1024 * 1024))
         stConvertedSize = String.format("%,.000d", dblConversionSize / 1024 / 1024 / 1024) + " TiB";
    I've also tried using
         String.valueOf(dblConversionSize / 1024 / 1024 / 1024) + " TiB";
    However, the formatting is failing and I'm either getting a format exception or the result is displayed as a number with no decimal component.
    Anyone have a recipe for this?
    Thanks,
    Tim

    TOLIS Tim wrote:
    Thanks, but the reason for using Double is that the division math can leave me with values like 2.341 GiB.  I don't want to drop the values (or round) on the right side of the decimal point.
    Then you may look for DigDecimal which avoids digitization errors.
    NumberFormat will handle all subclasses of Number. You might need another specialization. Just look at the API which one is suitable.
    bye
    TPD

  • Convert byte to string - not working

    Hello. I'm having trouble figuring out this conversion. I want to check if a byte from a byte array is equal to a specified string (or character). This is the code that I have:
    byte byteArray[] = new byte[3];
    byte tempByte = byteArray[2];
    String tempString = tempByte.toString();
    The compilation error that I'm getting: byte cannot be dereferenced
    If you have any idea what I should do to fix this, please let me know.
    c00p

    Use this line instead:
    String tempString = Byte.toString(tempByte);
    You can't call a method on a primitive type of byte.

  • 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"

  • How to convert number to string in java

    hi how can i convert number to string in java
    something like
    public void Discription(Number ownerName){
    String.valueOf(ownerName);Edited by: adf009 on 2013/04/08 7:14 PM

    Yet another way of doing it is: ownerName.toString().
    If you are working in and IDE such as Netbeans or Eclipse, type a period after the object name. Wait a second or so. Eclipse/Netbeans Intellisense will show you a list of functions that object provides that you can choose from. toString() is one of them.

  • How to Convert JTextArea to String

    How would i convert JTextArea to string?

    elaborate, whats RTFAPI? I searched for it and got
    nothing.Since I'm not quite sure if you are being sarcastic, that translates to "read the f*cking application programmer interface". :)

Maybe you are looking for