Byte to string

byte[] bytearray=...............already initialised
String s="";
for(int i=0; i<bytearray.length; i++){
s+=( char )bytearray[ i ]+",";
Now how do i get back??????

bytearray = s.getBytes();Mark

Similar Messages

  • Conversion of byte into string

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

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

  • Encoded double byte characters string conversion

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

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

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

  • How to covert byte[] to String format

    I'm trying to print the reultset into a text file, but I'm having a prb converting byte[] to String.
    Here is my Code
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("C:\\MyFile.txt")));
    while (rs1.next()) {
    byte[] _id         = rs1.getBytes(1);
    String _FName   = rs1.getString(2);
    String _LName   = rs1.getString(3);
    out.print(_id);
    String s = String.valueOf(_id);
    out.println("-Sales_Acct--:"+s+"--Name--"+FName+"-Numb-"+LName);
    I'm supposed to get 0000690D ( byte[] value )but in the text file it is printing as [B@1add
    I donno what's wrong with my code!!
    your help is greatly appreciated!

    http://forum.java.sun.com/thread.jsp?forum=48&thread=143531
    do you two know one another?

  • Byte to String conversion for encryption and decryption

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

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

  • File Bytes to String

    I'm trying to decode a file, when i use this codepublic void returnFile(String filename) throws FileNotFoundException, IOException {
    //       A FileInputStream is for bytes
           FileInputStream fis = null;
           try {
                fis = new FileInputStream(filename);
                byte[] buf = new byte[4 * 1024];  // 4K buffer
                int bytesRead;
                while ((bytesRead = fis.read(buf)) != -1) {
                     out.write(buf, 0, bytesRead);
           finally {
                if (fis != null) fis.close();
      }with the result beeing printed directly,
    but in an other case i don't have access to the out variable, so i want to return a string from a function, so i have thispublic static String returnFile2(String filename)
         throws FileNotFoundException, IOException {
    //          A FileInputStream is for bytes
              FileInputStream fis = null;
              StringBuffer buffer = new StringBuffer();
              try {
                   fis = new FileInputStream("C:/eclipse/workspace/rbtTranform/WebContent/images/15x15/V.gif");
                   byte[] buf = new byte[4 * 1024];  // 4K buffer
                   int bytesRead;
                   while ((bytesRead = fis.read(buf)) != -1) {
                        buffer.append(new String(buf).trim());
              finally {
                   if (fis != null) fis.close();
              return buffer.toString();
         }The problem is that in this second funcion, i return the file contents as a String, they are not like in the first function, and i can't "re-encode" the data back to original file (as i can with the first function)
    Can anyone help me?

    I want to make a MultiPart Response, i am using this in a XSLT file that call a function that is supposed to take a file and return its contents as a String (the second method i posted)
    I can't use the first one, because from the XSLT i can't send the out parameter, so that i could write on it
    That's also why i can't handle and image as an image
    It's a bit confusing i know
    But if you could gimme a hint...

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

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

  • Byte[ ]    and    String

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

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

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

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

  • Convert a byte/Byte - HEX STRING ?

    Hi ,
    My Problem is , I want to convert a byte/Byte value to hex string. If there is any way to convert bytes to hex strings then please tell me.
    please help me.

    Integer.toHexString(byteValue);
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html

  • Handling unicode and multi-byte/ANSI strings in same application

    I'm creating my environment handle using OCIEnvNlsCreate so all strings passed to/from oracle are supposed to be in wide string format.
    This is fine until I want to bind a variable that contains an ANSI character string. My application can use mixed string types.
    Which SQLT_ type do I use to bind my ANSI character string? What's the difference between SQLT_STR and SQLT_AVC?
    Or do I have to convert each ANSI string to a wide string before I bind?
    The SQL Server ODBC API handles this problem without any trouble by specifying the data type when binding to SQL_VARCHAR or SQL_WVARCHAR.
    Any help greatly appreciated as I'm totally stuck!
    Thanks,
    John

    Here's the relevant para from the documentation:
    Specifying Character Sets in OCI
    Use the OCIEnvNlsCreate function to specify client-side database and national character sets when the OCI environment is created.This function allows users to set character set information dynamically in applications, independent of the NLS_LANG and NLS_NCHAR initialization parameter settings. In addition, one application can initialize several environment handles for different client environments in the same server environment.
    Any Oracle character set ID except AL16UTF16 can be specified through the OCIEnvNlsCreate function to specify the encoding of metadata, SQL CHAR data, and SQL NCHAR data. Use OCI_UTF16ID in the OCIEnvNlsCreate function to specify UTF-16 data.
    Can somebody please tell me what I can set charset or ncharset to apart from OCI_UTF16ID or zero and hence make the call to OCIEnvNlsCreate return OCI_SUCCESS.
    Thanks,
    John

Maybe you are looking for