Converting byte arrays to Strings

Why oh why are there so many posts where the problem is the result of assuming bytes are characters?
Is it because many new forum members come from a 'C' or VB background?
Is it because Computer Science teaches bytes <-> characters?

Might it be because persons are so used to ascii
tables?I suppose this has to be high on the list of reasons!

Similar Messages

  • What is the best way to convert a cluster into byte array or string

    I'm writing a program that sends UDP packets and I've defined the data I want to send via large clusters (with u8/u16/u32 numbers, u8/u16/u32 arrays, and nested clusters). Right before sending the data, I need to convert the clusters either into strings or byte arrays. The flatten to string function is almost perfect for this purpose. However, it's appending lengths to arrays and strings which renders this method useless, as far as I can tell. 
    As I have many of these clusters, I would rather not hard code the unbundle by names and converting/typecasting to byte arrays or strings for each one. 
    Is there a feature or tool I am overlooking? 
    Thank you! 

    deceased wrote:
    Flatten to string has a boolean input of "Prepend string or array size" ... The default value is true.
    That only specifies if a string or array size should be prepended if the outermost data element is a string or array. For embedded strings or arrays it has no influence. This is needed for the Unflatten to be able to reconstruct the size of the embedded strings and arrays.
    The choice to represent the "Strings" (and Arrays) in the external protocol to LabVIEW strings (and arrays) is actually a pretty bad one unless there is some other element in the cluster that does define the length of the string. An external protocol always needs some means to determine how long the embedded string or array would be in order to decode the subsequent elements that follow correctly.
    Possible choices here are therefore:
    1) some explicit length in the protocol (usually prepended to the actual string or array)
    2) a terminating NULL character for strings, (not very friendly for reliable protocol parsing)
    3) A fixed size array or string
    For number 1) and 2) you would always need to do some special processing unless the protocol happens to use explicitedly 32 bit integer length indicators directly prepended before the variable sized that.
    For number 3) the best representation in LabVIEW is actually a cluster with as many elements inside as the fixed size.
     

  • Convert byte array to table of int

    [http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print|http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print] Hello friends.
    I'm pretty new with PL/SQL.
    I have code that run well on MSSQL and I want to convert it to PL/SQL with no luck.
    The code converts byte array to table of int.
    The byte array is actually array of int that was converted to bytes in C# for sending it as parameter.
    The TSQL code is:
    CREATE FUNCTION dbo.GetTableVarchar(@Data image)
    RETURNS @DataTable TABLE (RowID int primary key IDENTITY ,
    Value Varchar(8000))
    AS
    BEGIN
    --First Test the data is of type Varchar.
    IF(dbo.ValidateExpectedType(103, @Data)<>1) RETURN
    --Loop thru the list inserting each
    -- item into the variable table.
    DECLARE @Ptr int, @Length int,
    @VarcharLength smallint, @Value Varchar(8000)
    SELECT @Length = DataLength(@Data), @Ptr = 2
    WHILE(@Ptr<@Length)
    BEGIN
    --The first 2 bytes of each item is the length of the
    --varchar, a negative number designates a null value.
    SET @VarcharLength = SUBSTRING(@Data, @ptr, 2)
    SET @Ptr = @Ptr + 2
    IF(@VarcharLength<0)
    SET @Value = NULL
    ELSE
    BEGIN
    SET @Value = SUBSTRING(@Data, @ptr, @VarcharLength)
    SET @Ptr = @Ptr + @VarcharLength
    END
    INSERT INTO @DataTable (Value) VALUES(@Value)
    END
    RETURN
    END
    It's taken from http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print.
    The C# code is:
    public byte[] Convert2Bytes(int[] list)
    if (list == null || list.Length == 0)
    return new byte[0];
    byte[] data = new byte[list.Length * 4];
    int k = 0;
    for (int i = 0; i < list.Length; i++)
    byte[] intBytes = BitConverter.GetBytes(list);
    for (int j = intBytes.Length - 1; j >= 0; j--)
    data[k++] = intBytes[j];
    return data;
    I tryied to convert the TSQL code to PL/SQL and thats what I've got:
    FUNCTION GetTableInt(p_Data blob)
    RETURN t_array --t_array is table of int
    AS
    l_Ptr number;
    l_Length number;
    l_ID number;
    l_data t_array;
    BEGIN
         l_Length := dbms_lob.getlength(p_Data);
    l_Ptr := 1;
         WHILE(l_Ptr<=l_Length)
         loop
              l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
              IF(l_ID<-2147483646)THEN
                   IF(l_ID=-2147483648)THEN
                        l_ID := NULL;
                   ELSE
                        l_Ptr := l_Ptr + 4;
                        l_ID := to_number( DBMS_LOB.SUBSTR(p_Data, 4,l_ptr));
                   END IF;
                   END IF;
    l_data(l_data.count) := l_ID;
              l_Ptr := l_Ptr + 4;
         END loop;
         RETURN l_data;
    END GetTableInt;
    This isn't work.
    This is the error:
    Error report:
    ORA-06502: PL/SQL: numeric or value error: character to number conversion error
    06502. 00000 - "PL/SQL: numeric or value error%s"
    I think the problem is in this line:
    l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
    but I don't know how to fix that.
    Thanks,
    MTs.

    I'd found the solution.
    I need to write:
    l_ID := utl_raw.cast_to_binary_integer( DBMS_LOB.SUBSTR(p_Data, 4,l_ptr));
    instead of:
    l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
    The performance isn't good, it's take 2.8 sec to convert 5000 int, but it's works.

  • Convert an array of strings into a single string

    Hi
    I am having trouble trying to figure out how to convert an array of strings into a single string.
    I am taking serial data via serial read in a loop to improve data transfer.  This means I am taking the data in chunks and these chunks are being dumped into an array.  However I want to combine all elements in the array into a single string (should be easy but I can't seem to make it work).
    In addition to this I would also like to then split the string by the comma separator so if any advice could be given on this it would be much appreciated.
    Many Thanks
    Ashley.

    Well, you don't even need to create the intermediary string array, right? This does exactly the same as CCs attachment:
    Back to your serial code:
    Why don't you built the array at the loop boundary? Same result.
    You could even built the string directly as shown here.
    Message Edited by altenbach on 12-20-2005 09:39 AM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    autoindexing.png ‏5 KB
    concatenate.png ‏5 KB
    StringToU32Array.png ‏3 KB

  • How to convert 1D array of string to string

    How to convert 1D array of string to string.

    Maximus00, as Pavel indicated, there is a lesser known feature of "Concatenate Strings" that does exactly what your code is doing if the input is an array of strings. In one step! See attached image.
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    ConcatenateArray ofStrings.gif ‏7 KB

  • How to send byte array and String values to servlet from Swing application

    Hi all,
    I am new to swing, servlet, and socket connection.
    I have swing application to draw images and some input data. I dont know to send to server.
    byte[] buf = baos.toByteArray();
    URL servletURL = new URL("http://10.70.70.1:8080/servlet/SaveImage)
    URLConnection conn = servletURL.openConnection();
    conn.setDoOutput(true);
    BufferedWriter out = new BufferedWriter( new OutputStreamWriter( conn.getOutputStream() ) );
    out.write(buf&a=aaaa&b=bbbbb);
    out.flush();
    out.close();
    can I do like this. Strings are received in server side perfect. but i cant get byte array data. Please help me.
    Thanks in advance.

    <img src="myservlet">
    In your myservlet:
    response.setContentType("image/jpeg");
    then write your image date via ImageIO that uses response output stream.

  • Convert Bytes Array to Binary?

    Hi,
    I have an array of Bytes .
    How can i convert it into Binary format ?
    Regards,
    Gaurav

    You must be misunderstanding something. There is no special format called "binary format".
    Explain to us why you want to convert your array of bytes into "binary format" and what "binary format" means according to you - then we might be able to help.

  • Would like some help converting an array of strings into multiple parsed string arrays

    Hello everyone.
    this is a very novice question and I sincerely apologize for that, but i need some direction!
    i have an array of strings:
    (('J01',), ('0', '0', '0', '1'))
    (('J02',), ('0', '1', '0', '1'))
    (('J03',), ('0', '0', '0', '0'))
    ect...
    i would like to know what are some of the best ways to gain access to this information (aka, parse it). The field lengths are not static and all those ones and zeros could very possibly be two digits at times (0 = off state, 1-100 = on state), so simply pulling characters out of a given position of the string will not always work.
    what i would like to achieve is to make either separate arrays for each desirable element, eg:
    array one:
    J01
    J02
    J03
    array two:
    0
    0
    0
    array three:
    0
    1
    0
    and so on.
    or maybe even a matrix (if that’s feasible).
    other than that I am totally up for suggestions!!
    thank you very much,
    Grant.

    Assuming fixed structure (not necessarily length of the different numbers or names).

  • How to convert char array to string

    sirs,
    i have written a method in java which will return a randomly generated string of a fixed length. i am creating one one character and inserting it into char array.
    at last i am converting it to string
    like this
    String newpass= pass.toString();// pass is a char array
    but problem is that the string is having different value what i hav generated.
    if i am doing like this..
    String newpass= new String(pass);// pass is a char array
    here newpass is having correct value but having some error
    error in the sense when i print
    System.out.println(newpass+"some text");
    "some text" is not printing
    can you suggest the better way

    /*this is my method */
    private String generateString(int len){
              char pass[] = new char[10];
              int cnt=0;
              int temp=0;
              Random randomGenerator = new Random();
                   for (int idx = 0; idx < 1000; ++idx)
                        temp = randomGenerator.nextInt(1000)%128;
                   if((temp>=65 && temp<=90)||(temp>=97 && temp<=122)||(temp>=48 && temp<=57))
                             pass[cnt]=(char)temp;
                             cnt++;               
                        if(cnt>=len) break;
                   String newpass= pass.toString();
                   String newpass1= new String(pass);
                   System.out.println("passed pass"+newpass+"as"+newpass1+"sa");
              return newpass;
    here newpass and newpass1 are having separate values
    why ??
    Edited by: Shovan on Jun 4, 2008 2:21 AM

  • How to get correct byte array from String

    I have a string which contains binary value from 0 to 255. Now, if I use String.getBytes(),all the chars in the string which range from 128 to 160 will be convert to 63.
    What's the problem?

    You're assuming that you're working with Ascii values.
    You're actually working with Unicode values.
    When you use getChar() on a String, you get back a 16bit integer, the unicode index. When you do a getBytes() the Unicode values get mapped back to the default codepage of your machine.
    Eg. on an english pc, the default locale is Windows latin, codepage 1252. On non-english pcs, it could be any encoding scheme.
    If you're on a machine set up for a chinese locale, then the Unicode
    values get mapped to your chinese codepage. The extended ascii values,
    above 127 may not be defined in your codepage.
    Try String.getBytes ( "Cp1252" );
    Although I suspect that, whatever you're trying to do, it's probably not the right approach....
    regards,
    Owen

  • Convertion of byte array in UTF-8 to GSM character set.

    I want to convert byte array in UTF-8 to GSM character set. Please advice How can I do that?

    String s = new String(byteArrayInUTF8,"utf-8");This will convert your byte array to a Java UNICODE UTF-16 encoded String on the assumption that the byte array represents characters encoded as utf-8.
    I don't understand what GSM characters are so someone else will have to help you with the second part.

  • Converting Image.jpg to byte array

    Hi,
    How do i convert a image (in any format like .jpeg, .bmp, gif) into a byte array
    And also vice versa, converting byte array to image format
    Thank you

    how about Class.getResourceAsStream(String name).read(byte[] b)?

  • Converting Array of string to an array of integers

    I have a problem converting a array of string to array of int's
    This is my code...
    String[] forminfo = request.getParameterValues("forsendur");
          int[] forminfoInt = Integer.parseInt(forminfo); This is the error message:
    Incompatible type for method. Can't convert java.lang.String[] to java.lang.String.
                          int[] forminfoInt = Integer.parseInt(forminfo);
                                                               ^can anyone help me with this?

    ParesIn methos returns a int buto not a int[]. You must iterate along the String array and perform the methos for each element setting the return value into the element of the int array
    Ej:
    int[] intArray = new int[stringArray.length]
    for(int i = 0; i < stringArray.length; i++)
    intArray[i] = Integer.parseInt(stringArray);

  • Converting array of strings using SCMS_STRING_TO_XSTRING

    Hello all,
    FM SCMS_STRING_TO_XSTRING can be used to convert a String to a XSTRING and then we can use FM SMUM_XML_PARSE to parse the XML.
    Now I will have a array of strings as an output from a web service and I need to parse them .. so the Function modules mentioned above are used for a single string but how to convert the array of strings??
    Please suggest me on how to proceed.
    Thanks in advance,
    Regards,
    Suman.

    Hi Raja,
    Thanks for your suggestion.
    I have yet to try this..I will update with the results.
    Regards,
    Suman.

  • How to shrink an array of strings

    I am working on the method shift() which is similar to the one found in Perl. This method will take an array of strings and return the first string in the array. The resulting array should shrink by one element.
    However, I am having trouble with getting the array modified.
    I will show the output and the code.
    java DemoShift a b c
    Args len: 3 Argument #0: a
    bcc
    Args len: 3 Argument #1: b
    ccc
    Args len: 3 Argument #2: c
    ccc
    As you can see, I expect the array to get smaller each time, but I was unsuccessful. I have tried the following approaches:
    1. Convert the array of strings into StringBuffer by using append() and adding some delimeter, and then then using toString().split()
    2. Use ArrayList class to change the array length
    3. System.arraycopy.
    Here is the code. Let me know what do I need to get the array "args" get shrinked every time.
    <pre>
    import java.util.*;
    import java.io.*;
    class DemoShift
        public static void main(String args[])
            for (int counter = 0; counter < args.length ; counter++)
                System.out.println("Args len: " + args.length + " Argument #" + counter + ": " + shift(args));
                for (String st:args) System.out.print (st);
                System.out.println();
        public static String shift(String... args)
            StringBuilder sb = new StringBuilder(args.length-1);
            String firstString = args[0];
            String temp[] = new String[args.length -1];
            for (int counter = 1; counter < args.length; counter++)                                             
                sb.append(args[counter]);                                                                       
                sb.append("MYSPLIT");                                                                           
            temp = sb.toString().split("MYSPLIT");                                                              
            System.arraycopy(temp, 0, args, 0, temp.length);
            return firstString;
        }Edited by: vadimsf on Oct 25, 2007 10:17 PM

    I didn't really pay much attention to your problem, but will this help?
         public static void main(String[] args) {
              String[] test = {"test1", "test2", "test3"};
              for (String s : shift(test))
                   System.out.println(s);
         public static String[] shift(String[] arr)
              String[] a = new String[arr.length - 1];
              for (int i = 1; i < arr.length; i++)
                   a[i - 1] = arr;
              return a;

Maybe you are looking for

  • IPHOTO 9 PARTIAL BACKUP

    After a bad experience using Time Machine with an external hard drive I decided to back up my photos to 2 DVDs, which I did. I would like to periodically backup only those items in iPhoto that have been added since the original backup, how do I selec

  • OIM Exchange Integration

    Hi All, I am trying to configure OIM with Exchange 2003, for this I am using exchange connector MSFT_Exchange_91100 with OIM 9101. I have copied the jar files to required directory and also imported the xml and according to the documentation I need n

  • Any idea of when Mac OS X 10.5 will be getting a Java Update, like 10.6/10.7?

    There are some security vunerabilities with existing Java plugins (which came with Mac OS 10.5 Java Update 10) Pls refer http://www.oracle.com/technetwork/topics/security/javacpufeb2012-366318.html for more info... Java in Snow Leopard and Lion were

  • Locking access to folders

    Hi I am wanting to lock some folders, so that other users on my localised network can't open them. I have tried changing the permissions to: everyone > no access but when testing they can still be opened. is there anyway to do this? any help would be

  • I recently had to do a restore system on my hp touchsmart due to some error, before i did it asked m

    Hi I recently had to do a system restore on my HP Touchsmart computer, before i commenced it asked me to back up all files onto storable discs, which i did using TDK-DVD+R discs x 2 since doing the restore it appears that i can not reload all the fil