Hex string conversion to ASCII Character string

I have a Hex String 494A4B4C and want this string to get converted in ASCII Character String. IJKL. How to do in Labview 8.5.

Here is a screenshot of the described code:
Ton
Message Edited by TCPlomp on 30-09-2009 01:35 PM
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!
Attachments:
Example_VI_BD.png ‏3 KB

Similar Messages

  • ASCII character/string processing and performance - char[] versus String?

    Hello everyone
    I am relative novice to Java, I have procedural C programming background.
    I am reading many very large (many GB) comma/double-quote separated ASCII CSV text files and performing various kinds of pre-processing on them, prior to loading into the database.
    I am using Java7 (the latest) and using NIO.2.
    The IO performance is fine.
    My question is regarding performance of using char[i] arrays versus Strings and StringBuilder classes using charAt() methods.
    I read a file, one line/record at a time and then I process it. The regex is not an option (too slow and can not handle all cases I need to cover).
    I noticed that accessing a single character of a given String (or StringBuilder too) class using String.charAt(i) methods is several times (5 times+?) slower than referring to a char of an array with index.
    My question: is this correct observation re charAt() versus char[i] performance difference or am I doing something wrong in case of a String class?
    What is the best way (performance) to process character strings inside Java if I need to process them one character at a time ?
    Is there another approach that I should consider?
    Many thanks in advance

    >
    Once I took that String.length() method out of the 'for loop' and used integer length local variable, as you have in your code, the performance is very close between array of char and String charAt() approaches.
    >
    You are still worrying about something that is irrevelant in the greater scheme of things.
    It doesn't matter how fast the CPU processing of the data is if it is faster than you can write the data to the sink. The process is:
    1. read data into memory
    2. manipulate that data
    3. write data to a sink (database, file, network)
    The reading and writing of the data are going to be tens of thousands of times slower than any CPU you will be using. That read/write part of the process is the limiting factor of your throughput; not the CPU manipulation of step #2.
    Step #2 can only go as fast as steps #1 and #3 permit.
    Like I said above:
    >
    The best 'file to database' performance you could hope to achieve would be loading simple, 'known to be clean', record of a file into ONE table column defined, perhaps, as VARCHAR2(1000); that is, with NO processing of the record at all to determine column boundaries.
    That performance would be the standard you would measure all others against and would typically be in the hundreds of thousands or millions of records per minute.
    What you would find is that you can perform one heck of a lot of processing on each record without slowing that 'read and load' process down at all.
    >
    Regardless of the sink (DB, file, network) when you are designing data transport services you need to identify the 'slowest' parts. Those are the 'weak links' in the data chain. Once you have identified and tuned those parts the performance of any other step merely needs to be 'slightly' better to avoid becoming a bottleneck.
    That CPU part for step #2 is only rarely, if every the problem. Don't even consider it for specialized tuning until you demonstrate that it is needed.
    Besides, if your code is properly designed and modularized you should be able to 'plug n play' different parse and transform components after the framework is complete and in the performance test stage.
    >
    The only thing that is fixed is that all input files are ASCII (not Unicode) characters in range of 'space' to '~' (decimal 32-126) or common control characters like CR,LF,etc.
    >
    Then you could use byte arrays and byte processing to determine the record boundaries even if you then use String processing for the rest of the manipulation.
    That is what my framework does. You define the character set of the file and a 'set' of allowable record delimiters as Strings in that character set. There can be multiple possible record delimiters and each one can be multi-character (e.g. you can use 'XyZ' if you want.
    The delimiter set is converted to byte arrays and the file is read using RandomAccessFile and double-buffering and a multiple mark/reset functionality. The buffers are then searched for one of the delimiter byte arrays and the location of the delimiter is saved. The resulting byte array is then saved as a 'physical record'.
    Those 'physical records' are then processed to create 'logical records'. The distinction is due to possible embedded record delimiters as you mentioned. One logical record might appear as two physical records if a field has an embedded record delimiter. That is resolved easily since each logical record in the file MUST have the same number of fields.
    So a record with an embedded delimiter will have few fields than required meaning it needs to be combined with one, or more of the following records.
    >
    My files have no metadata, some are comma delimited and some comma and double quote delimited together, to protect the embedded commas inside columns.
    >
    I didn't mean the files themselves needed to contain metadata. I just meant that YOU need to know what metadata to use. For example you need to know that there should ultimately be 10 fields for each record. The file itself may have fewer physical fields due to TRAILING NULLCOS whereby all consecutive NULL fields at the of a record do not need to be present.
    >
    The number of columns in a file is variable and each line in any one file can have a different number of columns. Ragged columns.
    There may be repeated null columns in any like ,,, or "","","" or any combination of the above.
    There may also be spaces between delimiters.
    The files may be UNIX/Linux terminated or Windows Server terminated (CR/LF or CR or LF).
    >
    All of those are basic requirements and none of them present any real issue or problem.
    >
    To make it even harder, there may be embedded LF characters inside the double quoted columns too, which need to be caught and weeded out.
    >
    That only makes it 'harder' in the sense that virtually NONE of the standard software available for processing delimited files take that into account. There have been some attempts (you can find them on the net) for using various 'escaping' techniques to escape those characters where they occur but none of them ever caught on and I have never found any in widespread use.
    The main reason for that is that the software used to create the files to begin with isn't written to ADD the escape characters but is written on the assumption that they won't be needed.
    That read/write for 'escaped' files has to be done in pairs. You need a writer that can write escapes and a matching reader to read them.
    Even the latest version of Informatica and DataStage cannot export a simple one column table that contains an embedded record delimiter and read it back properly. Those tools simply have NO functionality to let you even TRY to detect that embedded delimiters exist let alone do any about it by escaping those characters. I gave up back in the '90s trying to convince the Informatica folk to add that functionality to their tool. It would be simple to do.
    >
    Some numeric columns will also need processing to handle currency signs and numeric formats that are not valid for the database inpu.
    It does not feel like a job for RegEx (I want to be able to maintain the code and complex Regex is often 'write-only' code that a 9200bpm modem would be proud of!) and I don't think PL/SQL will be any faster or easier than Java for this sort of character based work.
    >
    Actually for 'validating' that a string of characters conforms (or not) to a particular format is an excellent application of regular expressions. Though, as you suggest, the actual parsing of a valid string to extract the data is not well-suited for RegEx. That is more appropriate for a custom format class that implements the proper business rules.
    You are correct that PL/SQL is NOT the language to use for such string parsing. However, Oracle does support Java stored procedures so that could be done in the database. I would only recommend pursuing that approach if you were already needing to perform some substantial data validation or processing the DB to begin with.
    >
    I have no control over format of the incoming files, they are coming from all sorts of legacy systems, many from IBM mainframes or AS/400 series, for example. Others from Solaris and Windows.
    >
    Not a problem. You just need to know what the format is so you can parse it properly.
    >
    Some files will be small, some many GB in size.
    >
    Not really relevant except as it relates to the need to SINK the data at some point. The larger the amount of SOURCE data the sooner you need to SINK it to make room for the rest.
    Unfortunately, the very nature of delimited data with varying record lengths and possible embedded delimiters means that you can't really chunk the file to support parallel read operations effectively.
    You need to focus on designing the proper architecture to create a modular framework of readers, writers, parsers, formatters, etc. Your concern with details about String versus Array are way premature at best.
    My framework has been doing what you are proposing and has been in use for over 20 years by three different major nternational clients. I have never had any issues with the level of detail you have asked about in this thread.
    Throughout is limited by the performance of the SOURCE and the SINK. The processing in-between has NEVER been an issu.
    A modular framework allows you to fine-tune or even replace a component at any time with just 'plug n play'. That is what Interfaces are all about. Any code you write for a parser should be based on an interface contract. That allows you to write the initial code using the simplest possible method and then later if, and ONLY if, that particular module becomes a bottlenect, replace that module with one that is more performant.
    Your intital code should ONLY use standard well-established constructs until there is a demonstrated need for something else. For your use case that means String processing, not byte arrays (except for detecting record boundaries).

  • Ascii character conversion

    I need to decode a DMM serial connection. It spits out ascii looking charactors. The DMM is RadioShack DMM catalog # 22-812. Any ideas to convert ascii to something readable?

    Btw, I tried using a "format value" in the string conversion pallette with the string specifier (%s). This does not decode the characters.

  • Conversion failed when converting date and/or time from character string

    Hi experts,
    I'm trying running a query in Microsoft Query but it gives the following error message:
    "conversion failed when converting date and/or time from character string"
    when asks me the data I'm inserting 31-01-2014
    i've copy the query form the forum:
    SELECT T1.CardCode, T1.CardName, T1.CreditLine, T0.RefDate, T0.Ref1 'Document Number',
         CASE  WHEN T0.TransType=13 THEN 'Invoice'
              WHEN T0.TransType=14 THEN 'Credit Note'
              WHEN T0.TransType=30 THEN 'Journal'
              WHEN T0.TransType=24 THEN 'Receipt'
              END AS 'Document Type',
         T0.DueDate, (T0.Debit- T0.Credit) 'Balance'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')<=-1),0) 'Future'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=0 and DateDiff(day, T0.DueDate,'[%1]')<=30),0) 'Current'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>30 and DateDiff(day, T0.DueDate,'[%1]')<=60),0) '31-60 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>60 and DateDiff(day, T0.DueDate,'[%1]')<=90),0) '61-90 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>90 and DateDiff(day, T0.DueDate,'[%1]')<=120),0) '91-120 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=121),0) '121+ Days'
    FROM JDT1 T0 INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
    WHERE (T0.MthDate IS NULL OR T0.MthDate > ?) AND T0.RefDate <= ? AND T1.CardType = 'C'
    ORDER BY T1.CardCode, T0.DueDate, T0.Ref1

    Hi,
    The above error appears due to date format is differnt from SAP query generator and SQL server.
    So you need convert all date in above query to SQL server required format.
    Try to convert..let me know if not possible.
    Thanks & Regards,
    Nagarajan

  • Error "Conversion failed when converting date and/or time from character string" to execute one query in sql 2008 r2, run ok in 2005.

    I have  a table-valued function that run in sql 2005 and when try to execute in sql 2008 r2, return the next "Conversion failed when converting date and/or time from character string".
    USE [Runtime]
    GO
    /****** Object:  UserDefinedFunction [dbo].[f_Pinto_Graf_P_Opt]    Script Date: 06/11/2013 08:47:47 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE   FUNCTION [dbo].[f_Pinto_Graf_P_Opt] (@fechaInicio datetime, @fechaFin datetime)  
    -- Declaramos la tabla "@Produc_Opt" que será devuelta por la funcion
    RETURNS @Produc_Opt table ( Hora datetime,NSACOS int, NSACOS_opt int)
    AS  
    BEGIN 
    -- Crea el Cursor
    DECLARE cursorHora CURSOR
    READ_ONLY
    FOR SELECT DateTime, Value FROM f_PP_Graficas ('Pinto_CON_SACOS',@fechaInicio, @fechaFin,'Pinto_PRODUCTO')
    -- Declaracion de variables locales
    DECLARE @produc_opt_hora int
    DECLARE @produc_opt_parc int
    DECLARE @nsacos int
    DECLARE @time_parc datetime
    -- Inicializamos VARIABLES
    SET @produc_opt_hora = (SELECT * FROM f_Valor (@fechaFin,'Pinto_PRODUC_OPT'))
    -- Abre y se crea el conjunto del cursor
    OPEN cursorHora
    -- Comenzamos los calculos 
    FETCH NEXT FROM cursorHora INTO @time_parc,@nsacos
    /************  BUCLE WHILE QUE SE VA A MOVER A TRAVES DEL CURSOR  ************/
    WHILE (@@fetch_status <> -1)
    BEGIN
    IF (@@fetch_status = -2)
    BEGIN
    -- Terminamos la ejecucion 
    BREAK
    END
    -- REALIZAMOS CÁLCULOS
    SET @produc_opt_parc = (SELECT dbo.f_P_Opt_Parc (@fechaInicio,@time_parc,@produc_opt_hora))
    -- INSERTAMOS VALORES EN LA TABLA
    INSERT @Produc_Opt VALUES (@time_parc,@nsacos, @produc_opt_parc)
    -- Avanzamos el cursor
    FETCH NEXT FROM cursorHora INTO @time_parc,@nsacos
    END
    /************  FIN DEL BUCLE QUE SE MUEVE A TRAVES DEL CURSOR  ***************/
    -- Cerramos el cursor
    CLOSE cursorHora
    -- Liberamos  los cursores
    DEALLOCATE cursorHora
    RETURN 
    END

    You can search the forums for that error message and find previous discussions - they all boil down to the same problem.  Somewhere in your query that calls this function, the code invoked implicitly converts from string to date/datetime.  In general,
    this works in any version of sql server if the runtime settings are correct for the format of the string data.  The fact that it works in one server and not in another server suggests that the query executes with different settings - and I'll assume for
    the moment that the format of the data involved in this conversion is consistent within the database/resultset and consistent between the 2 servers. 
    I suggest you read Tibor's guide to the datetime datatype (via the link to his site below) first - then go find the actual code that performs this conversion.  It may not be in the function you posted, since that function also executes other functions. 
    You also did not post the query that calls this function, so this function may not, in fact, be the source of the problem at all. 
    Tibor's site

  • SAP query error - 1). [Microsoft][SQL Server Native Client 10.0][SQL Server]Conversion failed when converting date and/or time from character string.  'Received Alerts' (OAIB)

    SAP query error - 1). [Microsoft][SQL Server Native Client 10.0][SQL Server]Conversion failed when converting date and/or time from character string.  'Received Alerts' (OAIB)
    SELECT    
    CASE WHEN T0.DocStatus = 'O' THEN 'OPEN'
    WHEN T0.DocStatus = 'C' THEN 'CLOSED'  END  AS 'Document Status',
    T0.DocDate AS 'Posting Date',
    T0.DocNum AS 'Doc.No',
    T0.NumAtCard,
    T0.TransId AS 'Trans. No.',
    T0.Comments AS 'Remarks',
    T0.CardCode AS 'Offset Acct',
    T0.CardName AS 'Offset Acct Name',
    sum(T0.DocTotal) + (T0.WTSum) as 'DocTotal',
    T3.DueDate AS 'Cheque Date',
    T3.CheckSum AS 'Amount'
    FROM         ODPO AS T0 LEFT OUTER JOIN
                          VPM2 AS T1 ON T0.ObjType = T1.InvType AND T0.DocEntry = T1.DocEntry LEFT OUTER JOIN
         OVPM AS T2 ON T2.DocEntry = T1.DocNum LEFT OUTER JOIN
                          VPM1 AS T3 ON T2.DocEntry = T3.DocNum
    where T0.DocDate>='[%0]' and T0.DocDate<='[%1]'

    Hi,
    Try this:
    SELECT   
    CASE WHEN T0.DocStatus = 'O' THEN 'OPEN'
    WHEN T0.DocStatus = 'C' THEN 'CLOSED'  END  AS 'Document Status',
    T0.DocDate AS 'Posting Date',
    T0.DocNum AS 'Doc.No',
    T0.NumAtCard,
    T0.TransId AS 'Trans. No.',
    T0.Comments AS 'Remarks',
    T0.CardCode AS 'Offset Acct',
    T0.CardName AS 'Offset Acct Name',
    sum(T0.DocTotal) + (T0.WTSum) as 'DocTotal',
    T3.DueDate AS 'Cheque Date',
    T3.CheckSum AS 'Amount'
    FROM         ODPO  T0 LEFT OUTER JOIN
                          VPM2  T1 ON T0.ObjType = T1.InvType AND T0.DocEntry = T1.DocEntry
    LEFT OUTER JOIN
         OVPM  T2 ON T2.DocEntry = T1.DocNum LEFT OUTER JOIN
                          VPM1  T3 ON T2.DocEntry = T3.DocNum
    where T0.DocDate >= '[%0]' and T0.DocDate <='[%1]'
    group by T0.DocStatus,T0.DocDate ,
    T0.DocNum ,
    T0.NumAtCard,
    T0.TransId ,
    T0.Comments ,
    T0.CardCode,
    T0.CardName ,
    T0.WTSum ,
    T3.DueDate ,
    T3.CheckSum
    Thanks & Regards,
    Nagarajan

  • How to convert character string into ascii format correctly

    dear all
    I'm using encryption technique in my application(oracle formas 6i). character stream convert to the ascii format and add some numeric value and again convert to the character format
    >>>>
    here I'm using ASCII and CHR functions.
    >>>>
    .net program also using same algorithm to encrypt this password.....finally both the character strings are not equel.(This happens if the character string's ascii value greater than 127. otherwise both are equel).
    pls give me a solution for this
    thanks and regards
    buddhike

    hir dear
    do u want to encrypt & dcrypt your password.which version of oracle you are using
    first store these procedure in Oracle Databases: dbms_obfuscation_toolkit, dbms_crypto, Transparent Data Encryption
    now u can use these procedure to encrypt & dcrypt your password
    if you any query about those procedures you can ask me
    best regard
    amk

  • Implicit character or charactered structure -- to String  Conversion

    Hi everybody,
    that sounds trivial but i am struggeling.... which is the most elegant way to do a implicit "To-String" Conversion in ABAP Objects...
    I have e.g.
        data lok_string type string.
        lok_string = wa.
        m_object->addline( lok_string ).
    which is working fine but is not elegant comaring with java.
    i want
        m_object->addline( wa ).
    but this don't go when "wa" is a structured workarea with many "type c"s in it (and only these).
    but since the explicit assignment "lok_string = wa." is working well, there could be a elegant  implicit  one?
    (m_object->addline expects a string variable.)
    Thank is aprreciated.
    Regards
    Hartmut

    Hi Sandra,
    this is the right direction.... but i would like to have it as an nested expression... (since implicit conversion seams to be impossible)
    like...
    m_object->addline( lcl_xxx=>tostring( wa_head ) )
    but this line above is not an valid abap objects syntax, unfortunatelly
    ... having:
    class lcl_xxx definition.
      public section.
        class-methods tostring importing charlike type clike returning value(string) type string.
    endclass.                   
    class lcl_xxx implementation.
      method tostring.
        string = charlike.
      endmethod.                   
    endclass.                   
    Best regards
    Hartmut

  • How do I convert the ASCII character % which is 25h to a hex number. I've tried using the scan value VI but get a zero in the value field.

    How do I convert the ASCII character % ,which is 25h, to a hex number 25h. I've tried using the scan value VI but I get a zero in the value field. 

    You can use String to Byte Array for this.

  • Binary/hex to ASCII character

    I am trying to send 8bits to a microcontroller, who understands ASCII characters. I am having trouble finding out how to convert my 8bits, or hex values, to the corresponding ASCII character....
    i.e. 01010101 binary = 55 hex = U char
    See the attached file...
    Attachments:
    Bin2Hex.vi ‏64 KB

    Graz, sorry i posted in the wrong forum at first, but thanks for replying.
    I am able to check what the microcontroller recieves, by activating 8 LED's corresponding to the byte. When using the attached file: Basic Write 1, wverything works great. The LED's will represent the byte exactly, for example 01010101 when sending the string "U" and so on..
    For my project i need to be able to specify 8 bits (or switches) individually, and send this to the microcontroller, in the manner of the attached file Bin2Hex...
    I basically just need to combine these two in the correct manner... something im yet to achieve..
    Attachments:
    Basic Write 1.vi ‏40 KB
    Bin2Hex.vi ‏56 KB

  • Adding zeros to a character string

    Hello friends,
    I want to add leading zeros for a field.
    the field is a character string.
    for example ,
    data: A(5) type c.
    now when A  = 'ab' (non-numeric value)
    i want this to be converted in '000ab'
    so, is there any standard Function module or any other way for doing this conversion ?
    I tried the FM   'CONVERSION_EXIT_ALPHA_INPUT' but this FM does not work for non-numeric inputs..
    Thanks.

    Hi,
    The packed field is transported right-justified to the character field, if required with a
    decimal point. The first position is reserved for the sign. Leading zeros appear as
    blanks. If the target field is too short, the sign is omitted for positive numbers. If this is still not sufficient, the field is truncated on the left. ABAP indicates the truncation with an asterisk (*). If you want the leading zeros to appear in the character field, use UNPACK instead of MOVE.
    UNPACK
    Converts variables from type P to type C.
    Syntax
    UNPACK <f> TO <g>.
    Unpacks the packed field <f> and places it in the string <g> with leading zeros. The opposite of PACK.
    Regards,
    Bhaskar

  • String Conversion

    In Word if I run "StrConv(FeeMemo.Addr.Text, 3)" on a test of "this is a test of string conversion" this function will convert this text to "This Is A Test Of String Conversion".
    I wonder if such functionality exist on JaveScript for PDF? and if there is where would you put it?
    Thanks in advance for your help...
    Regards
    Jeff

    You can write a JavaScript function and place it in the document level JavaScript or as a folder level script.
    You will have to split the text sting by the space character and then go through each element of the array and then force the first character of each element to an upper case value. You can then reassemble the elements with the spaces between them.

  • Unicode to String Conversion

    Dear all,
    I'm trying to get the String from unicode, previously i'm converting the String to Unicode like below,
    String s = "\\u"+Integer.toHexString(s.charAt(0));
    Which is giving me the same what i appended above even after Conversion using UTF-8.
    If i do String s ="\u30f3"
    It is giving me correct character. But my problem is i'm getting the latter part i.e hexString latter in the run time...through Integer.toHexString..
    i can't add this as a character.. so it is taking as a two different strings..
    How to handle this situation..
    Hope i can find the answer,
    Thanks in advance,
    Srinivas N

    Below is my IOUtils class. In particular, see the loadTextFile method for an example of how to read a UTF file, and the isUTF method to detect if a file is Unicode
    You will not be able to compile this class unless you have my InfoFetcher class. You should be able to find a reference to this class by searching google for "InfoFetcher tjacobs01"
    You are welcome to use and modify this class, but please don't change the package or take credit for it as your own work
    package tjacobs.io;
    import java.awt.Component;
    import java.io.*;
    import java.net.URL;
    import java.net.URLConnection;
    import java.text.MessageFormat;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import javax.swing.JOptionPane;
    import javax.swing.JTable;
    import javax.swing.table.TableModel;
    import tjacobs.io.InfoFetcher.FetcherListener;
    * IOUtils class
    * This is an important class that I use a lot.<p>
    * has a lot of static utilities. Most should be fairly self-explanatory
    public class IOUtils {
         public static final int DEFAULT_BUFFER_SIZE = (int) Math.pow(2, 20); //1 MByte
         public static final int DEFAULT_WAIT_TIME = 30000;
         public static final boolean ALWAYS_BACKUP = false;
         public static String loadTextFile(File f) throws IOException {
              return loadTextFile(f, isUTF16(f));
         public static String loadTextFile(File f, boolean UTF16) throws IOException {
              BufferedReader br = !UTF16 ?
                        new BufferedReader(new FileReader(f)) :
                        new BufferedReader(
                             new InputStreamReader(new FileInputStream(f),
                                                   "UTF-16"));
              int length = (int) f.length();
              char data[] = new char[!UTF16?(int)length : ((int)length) / 2 - 1];
              int got = 0;
              do {
                   got += br.read(data, got, data.length - got);
              while (got < data.length);
              return new String(data);
         public static InfoFetcher loadData(InputStream in) {
              byte buf[] = new byte[DEFAULT_BUFFER_SIZE]; // 1 MByte
              return loadData(in, buf);
         public static InfoFetcher loadData(InputStream in, byte buf[]) {
              return loadData(in, buf, TimeOut.DEFAULT_WAIT_TIME);
         public static InfoFetcher loadData(InputStream in, byte buf[], int waitTime) {
              return new InfoFetcher(in, buf, waitTime);
         public static InfoFetcher loadData(InputStream in, int initBufLength, int waitTime) {
              return loadData(in, new byte[initBufLength], waitTime);
         public static InfoFetcher loadData(File f) throws FileNotFoundException{
              //if (!f.exists()) throw new FileNotFoundException(f.getAbsolutePath());
              //create the inputstream first so that we can generate the FileNotFoundException right away
              InputStream in = new BufferedInputStream(new FileInputStream(f));
              long len = f.length();
              if (len > Integer.MAX_VALUE) {
                   throw new RuntimeException("File size exceeds maximum size for a byte buffer");
              return loadData(in, (int) len, TimeOut.NO_TIMEOUT);
         public static InfoFetcher loadData(URL url) throws IOException{
              return loadData(url.openConnection());
         public static InfoFetcher loadData(URLConnection conn) throws IOException {
              int size = conn.getContentLength();
              if (size < 0) return loadData(conn.getInputStream(), 2000, DEFAULT_WAIT_TIME);
              return loadData(conn.getInputStream(), size, DEFAULT_WAIT_TIME);
          * Note: There is no guarentee that this method will
          * ever return. For instance, if you call loadAll on
          * an open socket connection it won't return until the
          * socket has closed
         public static String loadAllString(InputStream in) {
              InfoFetcher fetcher = loadData(in);
              fetcher.run();
              return new String(fetcher.buf, 0, fetcher.got);
          * Note: There is no guarentee that this method will
          * ever return. For instance, if you call loadAll on
          * an open socket connection it won't return until the
          * socket has closed
         public static byte[] loadAll(InputStream in) {
              InfoFetcher fetcher = loadData(in);
              return fetcher.readCompletely();
         public static void copyBufs(byte src[], byte target[]) {
              int length = Math.min(src.length, target.length);
              for (int i = 0; i < length; i++) {
                   target[i] = src;
         * Not threaded by default. If you need this to run
         * in a separate, create a new thread or runnable class
         * @param in
         * @param out
         public static void pipe (InputStream in, OutputStream out) {
              pipe (in, out, TimeOut.NO_TIMEOUT);
         * Not threaded by default. If you need this to run
         * in a separate, create a new thread or runnable class
         * @param in
         * @param out
         public static void pipe (InputStream in, final OutputStream out, int timeout) {
              pipe (in, out, timeout, false);
         private static class PipeFetcher implements FetcherListener {
              OutputStream out;
              InputStream in;
              public IOException ex;
              boolean closeWhenDone;
              public PipeFetcher (InputStream in, OutputStream out, boolean closeWhenDone) {
                   this.out = out;
                   this.closeWhenDone = closeWhenDone;
              public void fetchedMore(byte[] buf, int start, int end) {
                   try {
                        out.write(buf, start, end - start);
                   catch (IOException iox) {
                        ex = iox;
                        try {
                             in.close();
                             out.close();
                        catch (IOException iox2) {
                             iox2.printStackTrace();
              public void fetchedAll(byte[] buf) {
                   if (closeWhenDone) {
                        try {
                             out.close();
                        catch (IOException iox) {
                             iox.printStackTrace();
         * Not threaded by default. If you need this to run
         * in a separate, create a new thread or runnable class
         * @param in
         * @param out
         public static IOException pipe (final InputStream in, final OutputStream out, int timeout, final boolean closeWhenDone) {
              InfoFetcher info = new InfoFetcher (in, new byte[DEFAULT_BUFFER_SIZE], timeout);
              PipeFetcher pf = new PipeFetcher(in, out, closeWhenDone);
              info.addFetcherListener(pf);
              info.run();
              return pf.ex;
              info.addInputStreamListener(new InputStreamListener() {
                   public void gotMore(InputStreamEvent ev) {
                        try {
                             out.write(ev.getBytes(), ev.getStart(), ev.getBytesRetrieved() - ev.getStart());
                        catch (IOException iox) {
                             System.err.println ("Pipe closing");
                   public void gotAll(InputStreamEvent ev) {}
              Thread t= new Thread (info);
              t.start();
         public static byte[] expandBuf(byte array[]) {
              return expandBuf(array, array.length * 2);
         public static byte[] expandBuf(byte array[], int newlength) {
              byte newbuf[] = new byte[newlength];
              copyBufs(array, newbuf);
              return newbuf;
         public static byte[] trimBuf(byte[] array, int size) {
              byte[] newbuf = new byte[size];
              for (int i = 0; i < size; i++) {
                   newbuf[i] = array[i];
              return newbuf;
         * @see getFileOutputStream(File, boolean)
         public static OutputStream getFileOutputStream(File file) throws IOException {
              return getFileOutputStream(file, true);
         * Convienience method for opening a FileOutputStream w/wo a buffer
         * makes sure that the file directory exists so this should always succeed.
         public static OutputStream getFileOutputStream(File file, boolean buffered) throws IOException {
              if (!file.exists() && !file.isDirectory()) {
                   confirmDirectoryExists(file.getParentFile());
              if (file.exists()) {
                   if (ALWAYS_BACKUP) {
                        file.renameTo(new File(file.getAbsolutePath() + "~"));
                   } else {
                        file.delete();
              file.createNewFile();
              OutputStream out = new FileOutputStream(file);
              if (buffered) {
                   out = new BufferedOutputStream(out);
              return out;
         * Confirms that a directory exists and makes it if it doesn't
         public static void confirmDirectoryExists(File dir) {
              if (!dir.exists()) {
                   confirmDirectoryExists(dir.getParentFile());
                   dir.mkdir();
              if (!dir.isDirectory()) {
                   confirmDirectoryExists(dir.getParentFile());
         public static OutputStream getFileOutputStream(String name) throws IOException {
              return getFileOutputStream(name, true);
         public static PrintStream getFilePrintStream(String file) throws IOException {
              return new PrintStream(getFileOutputStream(file));
         public static PrintStream getFilePrintStream(File file) throws IOException {
              return new PrintStream(getFileOutputStream(file));
         public static OutputStream getFileOutputStream(String name, boolean buffered) throws IOException {
              return getFileOutputStream(new File(name), buffered);
         * @param f if f is a directory it returns the absolue path to f otherwise it returns the absolute path to the directory f is in
         public static String getDirectory(File f) {
              if (f.isDirectory()) {
                   return f.getAbsolutePath();
              else {
                   return f.getParentFile().getAbsolutePath();
         * Get the file without the extension.
         * @see getFileNoExtension(String);
         public static String getFilenameNoExtension(File f) {
              return getFilenameNoExtension(f.getName());
         * Gets the file name without the extension
         * returns the whole file name if no '.' is found<br>
         * otherwise returns whatever's before the last .
         public static String getFilenameNoExtension(String s) {
              int idx = s.indexOf('.');
              if (idx == -1) {
                   return s;
              else {
                   return s.substring(0, idx);
         * gets the file extension
         * if a '.' character is found it returns what's after the last .
         * if not, it returns the empty string
         public static String getFileExtension(String s) {
              int idx = s.lastIndexOf('.');
              if (idx == -1) {
                   return "";
              else {
                   return s.substring(idx + 1);
         * @see getFileExtension(String)
         public static String getFileExtension(File f) {
              return getFileExtension(f.getName());
         * Delete everything in a directory. Recursively deletes all sub-directories
         public static void deleteDirectory (File f, Component parent) {
              if (!f.isDirectory()) {
                   throw new RuntimeException("File " + f.getAbsolutePath() + " is not a directory!");
              int val = JOptionPane.showConfirmDialog(parent, "Confirm Delete " + f.getAbsolutePath(), "Confirm Delete " + f.getAbsolutePath(), JOptionPane.OK_CANCEL_OPTION);
              if (val == JOptionPane.OK_OPTION) {
                   deleteAllFiles(f);
         private static void deleteAllFiles (File f) {
              //recursively delete all its contents
              if (!f.isDirectory()) {
                   //throw new RuntimeException("File " + f.getAbsolutePath() + " is not a directory!");
                   f.delete();
              else {
                   File[] files = f.listFiles();
                   for (int i = 0; i < files.length; i++) {
                        if (files[i].equals(f) || files[i].equals(f.getParent())) {
                             continue;
                        deleteAllFiles(files[i]);
                   f.delete();
         * static utility method for copying a file to another location
         public static void copyFile (File src, File newParent) throws FileNotFoundException {
              if (!src.exists()) {
                   return;
              if (!newParent.exists()) {
                   newParent.mkdirs();
                   //throw new RuntimeException("Parent folder must exist");
              if (newParent.isDirectory()) {
                   File newFile = new File(newParent, src.getName());
                   if (src.isDirectory()) {
                        newFile.mkdir();
                        File children[] = src.listFiles();
                        for (int i = 0; i < children.length; i++) {
                             copyFile(children[i], newFile);
                   else {
                        //loadFile
                        InfoFetcher info = loadData(new FileInputStream(src));
                        final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newFile));
                        info.addInputStreamListener(new InputStreamListener() {
                             int lastbytes = 0;
                             public void gotMore(InputStreamEvent ev1) {
                                  try {
                                       out.write(ev1.getBytes(), lastbytes, ev1.getBytesRetrieved() - lastbytes);
                                       lastbytes = ev1.getBytesRetrieved();
                                  catch (IOException iox) {
                                       iox.printStackTrace();
                             public void gotAll(InputStreamEvent ev2) {
         * @deprecated use the Find class
         public static File find(Pattern p, File start) {
              return recursiveFind(start, null, p, true);
         * @deprecated use the Find class
         public static File find(Pattern p) {
              return find(p, new File("."));
         * @deprecated use the Find class
         private static File recursiveFind(File current, File cameFrom, Pattern p, boolean startDescending) {
              Matcher m = p.matcher(current.getName());
              if (m.matches()) {
                   return current;
              File[] files = current.listFiles();
              if (startDescending) {
                   File value = descend(current, cameFrom, p, startDescending);
                   if (value != null) return value;
                   return ascend(current, cameFrom, p, startDescending);
              else {
                   File value = ascend(current, cameFrom, p, startDescending);
                   if (value != null) return value;
                   return descend(current, cameFrom, p, startDescending);               
         * @deprecated use the Find class
         private static File ascend(File current, File cameFrom, Pattern p, boolean startDescending) {
              File par = current.getParentFile();
              if (par == null) {
                   return null;
              par = par.getAbsoluteFile();
              if (par.equals(cameFrom)) {
                   return null;
              return recursiveFind(par, current, p, false);
         * @deprecated use the Find class
         private static File descend(File current, File cameFrom, Pattern p, boolean startDescending) {
              File files[] = current.listFiles();
              if (files == null) {
                   return null;
              for (int i = 0; i < files.length; i++) {
                   File child = files[i];
                   if (child.equals(cameFrom)) {
                        continue;
                   File f = recursiveFind(child, current, p, true);
                   if (f != null) {
                        return f;
              return null;
         * Utility for saving a string to a file. Rather than have to set
         * up all the writers etc and trap exceptions, just returns a boolean
         * if it worked
         * <p>
         * @see saveData(File, byte[])
         public static boolean saveData(File f, String s) {
              return saveData(f, s.getBytes());
         * Utility for saving a string to a file. Rather than have to set
         * up all the writers etc and trap exceptions, just returns a boolean
         * if it worked
         public static boolean saveData(File f, byte[] data) {
              try {
                   OutputStream out = new BufferedOutputStream(new FileOutputStream(f));
                   out.write(data);
                   out.close();
              catch(IOException iox) {
                   iox.printStackTrace();
                   return false;
              return true;
         * Way to save a stream to a file. Not multithreaded.
         * Will block until the save is done
         * @param f
         * @param in
         * @return
         public static boolean saveData(File f, InputStream in) throws FileNotFoundException {
              return pipe(in, new FileOutputStream(f), TimeOut.NO_TIMEOUT, true) == null;
              //InfoFetcher fetcher = loadData(in);
    //          try {
    //               FileOutputStream out = new FileOutputStream(f);
    //               fetcher.addFetcherListener(new FetcherListener() {
    //                    public void fetchedMore(byte[] buf, int start, int end) {
    //                    public void fetchedAll(byte[] buf) {
    //          } catch (IOException iox) {
    //               iox.printStackTrace();
    //               return false;
    //          return true;
         * @deprecated use Find
         public static List<File> findAllFiles(Pattern p) {
              ArrayList<File> l = new ArrayList<File>();
              //File start = File.listRoots()[0];
              File start = new File("C:\\");
              return recursiveFindAll(start, null, p, true, l, 0);
              //l;
         * @deprecated use Find
         private static List recursiveFindAll(File current, File cameFrom, Pattern p, boolean startDescending, ArrayList<File> list, int level) {
              //System.out.println("" + level + " Scanning: " + current + "par: " + cameFrom);
              System.out.println("Scanning: " + current);
              Matcher m = p.matcher(current.getName());
              if (current.getName().equals("C:\\")) {
                   System.out.println("root");
                   try {
                        System.in.read();
                   catch (IOException iox) {}
              if (m.matches()) {
                   //return current;
                   list.add(current);
                   System.out.println("Adding " + current);
              File[] files = current.listFiles();
              if (startDescending) {
                   //File value = descend(current, cameFrom, p, startDescending);
                   descendAll(current, cameFrom, p, startDescending, list, level + 1);
                   //ascendAll(current, cameFrom, p, startDescending, list, level + 1);
                   //if (value != null) return value;
                   //return ascend(current, cameFrom, p, startDescending);
              else {
                   //ascendAll(current, cameFrom, p, startDescending, list, level + 1);
                   descendAll(current, cameFrom, p, startDescending, list, level + 1);
                   //File value = ascend(current, cameFrom, p, startDescending);
                   //if (value != null) return value;
                   //return descend(current, cameFrom, p, startDescending);               
              return list;
         * @deprecated use Find
         private static List ascendAll(File current, File cameFrom, Pattern p, boolean startDescending, ArrayList<File> list, int level) {
              File par = current.getParentFile();
              if (par == null) {
                   return list;
              par = par.getAbsoluteFile();
              if (par.equals(cameFrom)) {
                   return list;
              recursiveFindAll(par, current, p, false, list, level);
              return list;
         * @deprecated use Find
         private static File descendAll(File current, File cameFrom, Pattern p, boolean startDescending, ArrayList<File> list, int level) {
              File files[] = current.listFiles();
              if (files == null) {
                   return null;
              for (int i = 0; i < files.length; i++) {
                   File child = files[i];
                   if (child.equals(cameFrom)) {
                        continue;
                   recursiveFindAll(child, current, p, true, list, level);
              return null;
         public File getUniqueName(File f) {
              return getUniqueName (f, new MessageFormat("~{0,number,integer}"));
         public String getNameWOExtension(File f, boolean useAbsolute) {
              int idx = f.getName().indexOf(".");
              return (idx == -1) ? (useAbsolute ? f.getAbsolutePath() : f.getName()) : (useAbsolute ? f.getAbsolutePath() : f.getName()).substring(0, (useAbsolute ? f.getAbsolutePath().lastIndexOf(".") : f.getName().lastIndexOf(".")));
         public String getFileType (File f, boolean includeDot) {
              int idx = f.getName().lastIndexOf(".");
              return idx == -1 ? "" : f.getName().substring(idx + (includeDot ? 0 : 1));
         public File getUniqueName(File f, MessageFormat format) {
              String base = getNameWOExtension(f, true);
              String extension = getFileType(f, true);
              int count = 0;
              while (f.exists()) {
                   count++;
                   f = new File (base + format.format(new Object[] {Integer.valueOf(count)}) + extension);
              return f;
         public static boolean isUTF16 (File f) throws IOException {
              FileInputStream in = null;
              try {
                   if (!f.exists() || f.length() < 2) return false;
                   in = new FileInputStream(f);
                   byte b = (byte)in.read();
                   if (!(b == -1)) return false;
                   b = (byte) in.read();
                   return b == -2;
              finally {
                   if (in != null) in.close();
         public static boolean isUTF16(PushbackInputStream in) {
              boolean got1 = false, got2 = false;
              byte b = 0, b2 = 0;
              try {
                   b = (byte)in.read();
                   got1 = true;
                   if (!(b == -1 || b== -2)) {
                        return false;
                   b2 = (byte) in.read();
                   got2 = true;
                   return b == -1 ? b2 == -2 : b2 == -1;
              catch (IOException iox) {
                   iox.printStackTrace();
              finally {
                   try {
                        if (got1) {
                             in.unread(b);
                        if (got2) {
                             in.unread(b2);
                   } catch (IOException iox) {
                        iox.printStackTrace();
              return false;
         public void saveJTableToCSV(JTable table, File f) throws IOException {
              if (table == null || f == null) return;
              TableModel model = table.getModel();
              if (model == null) return;
              int rows = model.getRowCount();
              int columns = model.getColumnCount();
              PrintWriter pw = new PrintWriter(new FileWriter(f));
              for (int i = 0; i < rows; i++) {
                   for (int j = 0; j < columns; j++) {
                        Object o = model.getValueAt(i, j);
                        pw.print(o.toString());
                        if (j != columns - 1) {
                             pw.print(",");
                   pw.println();
         public static String getPathRelativeTo(File path, File relativeTo) {
              return getPathRelativeTo(path.getAbsolutePath(), relativeTo.getAbsolutePath());
         public static String getPathRelativeTo(String path, String relativeTo) {
              if (!path.startsWith(relativeTo)) return null;
              path = path.substring(relativeTo.length());
              if (path.startsWith(File.separator)) path = path.substring(File.separator.length());
              return path;

  • Numeric to string conversion

    I simply wish to take several numbers (controls) multiply them together but then I need the answer to be converted into the form of a string (ascii).
    Is there a VI available to do this ??

    Hi sammy,
          Right-click on the diagram and have a look around the String functions palette - specifically the String/Numeric conversion functions.
    Cheers.
    "Inside every large program is a small program struggling to get out." (attributed to Tony Hoare)

  • DEC to STRING conversion

    I can't seem to convert a DEC to a string.  This is a field defined in the dictionary by type TZNTSTMPS (DEC 15).  I tried the following to do the conversions:
    d_string = d_dec.
    write d_dec to d_string.
    CALL FUNCTION 'HRCM_AMOUNT_TO_STRING_CONVERT'
      EXPORTING
        betrg                         = d_dec
    *   WAERS                         = ' '
    *   NEW_DECIMAL_SEPARATOR         =
    *   NEW_THOUSANDS_SEPARATOR       =
    IMPORTING
       STRING                        = d_string.
    They all give me the same result which is an 8 character result with * being the first charcter.  Ultimately, what I need is to grab the first 8 characters as that is a date.
    Regards,
    Aaron

    Thanks for the idea.  ABI_TIMESTAMP_CONVERT_FROM works.
    Sorry, I thought it did.  It throws a run-time error telling me:
    Error analysis
        At the statment
             "WRITE src TO dest"
        only character-type data objects are supported at the argument position
        "dest", but no strings are supported (data types STRING and XSTRING).
        In this particular case, the operand "dest" has the
        type "g".
    It sounds like it doesn't like the DEC data type as an input but that is all I have to work with.
    Any ideas?
    Aaron
    Edited by: Aaron Shover on May 12, 2008 10:54 PM
    Sorry, it looks like LXHME_TIMESTAMP_CONVERT_FROM will work for me.
    Regards,
    Aaron
    Edited by: Aaron Shover on May 12, 2008 10:58 PM

Maybe you are looking for