Converting byte[] - String

Hi, how do I convert from byte[] to String and vice versa.
Is this correct for byte[]->String
ByteArrayOutputStream b = new ByteArrayOutputStream();
b.write(bytearray);
String s = b.toString();
and this for String->byte?
Writer out = new BufferedWriter(new OutputStreamWriter(new ByteArrayOutputStream()));
out.write(v);
byte[] b = v.getBytes());
Thanks!

Ok, that was a mess - take 2:
byte[] -> String :
byte[] byteArray = buildByteArray();
String strData = new String(byteArray);String -> byte[]
byte[] stringByteArray = strData.getBytes();Lee

Similar Messages

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

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

  • Converting a string to a byte

    I need to know how to convert a string of 1s and 0s into a byte.
    For example, if the string were "10010001", how would I make it a byte?
    I looked at the API, and the Byte class doesn't seem to have the capability to do this.
    (I realize that this is probably an unconventional way of doing it, but I'm required to do it this way.)
    Thanks in advance.

    Okay, I realized why I was having trouble.
    I even tried the parse method with the radix parameter thing before and it didn't work, but that was because I was using an invalid bit. (11001001)
    That bit came from a randomly (well, pseudo-randomly) generated bunch of bits, so I just assumed that it would be good.
    The project I'm working on is a one-time pad cipher, and that bit was generated by a method given to me by the professor. I remember now that he mentioned in passing something about how in this case, the first bit is used as a "sign bit" and that a "1" represents negative.
    Sorry for wasting your time / frustrating you. Thanks for your help though.

  • Creating a Function module to send XML Byte String

    Hi all,
    I have to create a Function module to get XML byte string.The internal table is dynamic coloums based on how many data selected as a importparameter.from the internal; table data I have to create a XML byte string as a output.Pl help me to proceed further.
    Thanks in Advance.
    Ram

    If i have your question right you need to convert an internal table of unknown type to an xml string then to a byte string.
    data xmlString type string.
    data xmlXString type xstring.
    call transformation id
       source
          table = internalTableYouWantToExport
       result
          xml xmlString.
    export xmlString to data buffer xmlXString.
    xmlString has the xml of the table and xmlXString contains the byte representation of the string.

  • Converting byte[] to Class without using defineClass() in ClassLoader

    so as to de-serialize objects that do not have their class definitions loaded yet, i am over-riding resolveClass() in ObjectInputStream .
    within resolveClass() i invoke findClass() on a network-based ClassLoader i created .
    within findClass() , i invoke
    Class remoteClass = defineClass(className, classImage, 0, classImage.length);
    and that is where i transform a byte[] into a Class , and then finally return a value for the resolveClass() method.
    this seems like a lengthy process. i mean, within resolveClass() i can grab the correct byte[] over the network.
    then, if i could only convert this byte[] to a Class within resolveClass() , i would never need to extended ClassLoader and over-ride findClass() .
    i assume that the only way to convert a byte[] to a Class is using defineClass() which is hidden deep within ClassLoader ? there is something going on under the hood i am sure. otherwise, why not a method to directly convert byte[] to a Class ? the byte[] representation of a Class always starts with hex CAFEBABE, and then i'm sure there is a standard way to structure the byte[] .
    my core issue is:
    i am sending objects over an ObjectInputStream created from a Socket .
    at the minimum, i can see that resolveClass() within ObjectInputStream must be invoked at least once .
    but then after that, since the relevant classes for de-serialization have been gotten over the network, i don't want to cascade all the way down to where i must invoke:
    Class remoteClass = defineClass(className, classImage, 0, classImage.length);
    again. so, right now, within resolveClass() i am using a Map<String, Class> to create the following class cache:
    cache.put(objectStreamClass.getName(), Class);
    once loaded, a class should stay loaded (even if its loaded in the run-time), i think? but this is not working. each de-serialization cascades down to defineClass() .
    so, i want to short-circuit the need to get the class within the resolveClass() method (ie. invoke defineClass() only once),
    but using a Map<String, Class> cache looks really stupid and certainly a hack.
    that is the best i can do to explain my issue. if you read this far, thanks.

    ok. stupid question:
    for me to use URLClassLoader , i am going to need to write a bare-bones HTTP server to handle the class requests, right?Wrong. You have to deploy one, but what's wrong with Apache for example? It's free, for a start.
    and, i should easily be able to do this using the com.sun.net.httpserver library, right?Why would you bother when free working HTTP servers are already available?

  • Retrive two byte string from indesign document

    Hello All ,
    I want to retrive two byte character string from indesign document.
    The way I use to retrive text from indesign I get it in WideString format which is 32 bit value.
    When I convert WideString to PMString I get string which represent characters
    eg. if WideString is E20F then
    PMString to GetCString is 45323046 //represent character position
    I want to put logic to left shift E with 4 and , OR next byte 2
    i.e E<<4 => E0 | 2 => E2 .
    But not able to retrive value of char as E but I get it as 45 which is character position in font.
    I want char *str should contained 1 byte->E2 and 2 byte->0F
    I want to convert WideString to 2 byte string , Please give solution.
    Regards,
    Pallavi.

    Hello T Schneider ,
    Thanks for Reply.
    using below code I am able to get Widestring in uchar16 * format.
    WideStringConstUTF32Iter iter = wsText.begin();
    WideStringConstUTF32Iter last = wsText.end();
    uchar16 * wstwobyte = (uchar16 *)malloc(sizeof(uchar16)* wstringlen);
    int k =0;
    while(iter != last)
    * wstwobyte = *iter;
    iter++;k++; wstwobyte++;
    *wstwobyte = (uchar16 )'\0';
    But how to end the uchar16 string, and iterate it again.
    I want to pass this string to a function having datatype for input string as usigned short * .

  • Converting byte from dec to hex

    Hi All,
    I'm having a problem converting byte from decimal to hex - i need the following result:
    if entered 127 (dec), the output should be 7f (hex).
    The following method fails, of course because of NumberFormatException.
        private byte toHexByte(byte signedByte)
            int unsignedByte = signedByte;
            unsignedByte &= 0xff;
            String hexString = Integer.toHexString(unsignedByte);
            BigInteger bigInteger = new BigInteger(hexString);
            //byte hexByte = Byte.parseByte(hexString);
            return bigInteger.byteValue();
        }

    get numberformatexception because a lot of hex digits cannot be transformed into int just like that (ie f is not a digit in decimal) heres some code that i used for a pdp11 assembler IDE... but this is for 16-bit 2s complement in binary/octal/decimal/hex , might be useful for reference as example though
        public static String getBase(short i, int base){
            String res = (i>=0)? Integer.toString((int)i,base)
                    : Integer.toString((int)65536+i,base) + " ("+Integer.toString((int)i,base)+")";
           StringBuffer pad= new StringBuffer();
            for(int x = 0; x < 16 - res.length() ; x++){
                pad.append("0");
            res = pad.toString() + res;
            return res;
        }

  • Is it possible to convert from string to variant?

    Hi!
    I would like to convert a text string to variant. I'm doing this because I would like to merge a couple of signals and then save all the signals in a lvm-file. Could someone please explain how to convert from text to variant, is it possible?
    Thanks in advance!
    Regards,
    Mattias
    Attachments:
    Merge signals.JPG ‏27 KB

    What you are attempting to do is possible, but might not give you the results you expect.  All you need to do is convert your string to an array of U8s using the String to Byte Array conversion primitive.  In the file, you will get a single character per line of the file expressed as the ASCII code.  When you read it, convert to U8s, then use Byte Array to String to get your string back.
    You may also want to read up on LVM files.  There are several places to put strings that work a little better than this.
    This account is no longer active. Contact ShadesOfGray for current posts and information.

  • How can I convert a string of hex values to a hex format string programatically?

    Is there a way to convert a string of the following format:
    1400010107070D0305006A01 ........           ("Normal display" string)
    programatically to:
    1400 0101 0707 0D03 05006A01 ..........      ("Hex display" striing)
    I need to do this in order to calculate a CRC16 value.
    See attached VIs
    Thank you.
    Solved!
    Go to Solution.
    Attachments:
    CMM_SN_MULTI.vi ‏50 KB
    CMM_CRC16_Calculator.vi ‏23 KB

    You can iterate over the string and use the String to Hex VI. If you work with two bytes of the string at a time you can get a U8 array of the desired binary values. Then when you are complete you can either work with the byte array of convert it back to a string using Byte Array to String.
    EDIT: GerdW typed faster than I did.
    Message Edited by Mark Yedinak on 03-18-2010 02:55 PM
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

  • Converting byte[] to unicode , help needed.

    need help, folks.
    i need to convert byte[] to unicode in byte[] form
    say i already loaded bunch of data
    byte[] bytes = {........} //bunch array of bytesand i read in the bytes as a stream in the native form.
    ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
    InputStreamReader isr = new InputStreamReader(stream,"GB18030");how do i get the bytes back in unicode ? i've been trying all kinds of methods, but doesnt seems to get what i want. i'm novice programmer, someone pls guide me ? thx.

                String s ;
              StringBuffer buffer = new StringBuffer();
              try {
                   ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
                   InputStreamReader isr = new InputStreamReader(stream, "GB18030");
                   Reader in = new BufferedReader(isr);
                   int ch;
                   while ((ch = in.read()) > -1) {
                   buffer.append((char)ch);
                   in.close();
                   s = buffer.toString();
                   bytes = s.getBytes("UnicodeLittle");
                   out.write(bytes);
              } catch (IOException e) {
                   e.printStackTrace();
                   //return null;
              }ah, nvm, i found a better solution to it, i'm little confused before this. the code above works fine.
    well, thx alot.

  • Convert C string in to BSTR with CA_CString​ToBSTR()

    I want to convert C string in to BSTR format with function CA_CStringToBSTR.
    I call an ActiveX function. In this function is CA_CStringToBSTR called.
    ------------ActiveX Function ---------------------
    HRESULT state;
    char buf[50]="0.0";
    BSTR bstr=0;
    state = CA_CStringToBSTR(buf, &bstr);
    return ......;(0x80070057 error code "Wrong parameter")
    Debuger after this Fun gives me the following result: state=0, bstr=0xXXXX(48)(No size Info)   [48=0x30='0']
    Then I get error from this ActiveX function. I think the problem is here with this CA-CStrng..... Function.
    Is that correct, what does this function? 

    You should never send C structs over the wire, otherwise you are expecting the other end to know (a) the source machine's byte order (b) the source machine's C compiler's alignment and padding rules (c) the source machine's C compiler's options in effect for the compilation of the program some of which can affect (b).
    Instead you should write each field separately in network byte order using htons(), htonl(), &c, or use something like XDR. If you do the former make sure the output is buffered so you don't write thousands of tinygrams.

  • Byte String conversion

    Problems reading a byte string. Has been a 16 bit number chopped into 2 bytes. Within Java we read the 2 bytes as below at the moment using an int []
    We sandwich it back together again but now and again the values seem to get muddled up. Example I can see the raw data sitting at 148 yet when the code is executed it says it is 28. Any ideas????
    String file = "HISTORY_data.out";
              m_historyInputStream=new FileInputStream( file );
              m_bufferedReader=new BufferedReader(new InputStreamReader( m_historyInputStream )) ;
              for (int i = 0; i <512; i++)
                   m_historyBuffer[i] = (byte)m_bufferedReader.read();
              // Read last startup ECG sector counter
              UpperByte = m_historyBuffer[72];
              LowerByte = m_historyBuffer[73];
              m_iECGSecStart = (UpperByte << 8) | (LowerByte & 0x00FF);

    When you use a Reader, the bytes are converted to characters, and in this process sometimes 2 or 3 bytes can be used to make up a character depending on the character encoding that is used with the Reader. This is usually some default character encoding, unless you provide your own. If you insist to use a Reader, and you want a 1 to 1 mapping between a byte and char, then use the ISO 8859-1 character encoding:
    m_bufferedReader = new BufferedReader(new InputStreamReader(m_historyInputStream, "8859_1"));But there is no need to do so. You would be better of using the BufferedOutputStream, and everything would have worked.
    And as mentioned before, there are other input/outputstreams that can convert 16-bit numbers to bytes and viceversa. Ints are 32-bit long, so when you read/write an int, it takes up 4 bytes, unless you convert it to a short. The primitives in java are signed, so you have to be careful with converting an int to a short and back to an int (you have to & with 0xFFFF if the short to int conversion should always be positive).

  • Hoe to convert a String to Triple DES Key

    Hi
    can Someone help me how to convert a string to TRipleDES key, some times the string can be less than
    24 bytes ( but DESedeKeySpec needs at least 24 bytes).
    thanks
    chintha

    I would take a slightly different approach than that offered by previous posts. This is from looking at what OpenSSL does for generating keys.
    1) Do a String.getBytes() from your password (or String.getBytes("UTF-8") if you are using other than ASCII).
    2) Generate a SHA-1 hash from the bytes. This gives you a 20 byte value.
    3) Compute a SHA-1 hash of the original hash and the password. This will give you another 20 byte value.
    4) Take the first 20 bytes from hash #1 and the first 4 bytes of hash #2 to get a 24 byte value.
    5) Give the 24 byte value odd parity (this means that each byte has an odd number of 1 bytes). You'll need to write a bit of your own code to do this.
    6) Finally, use this 24 byte, odd parity value to generate your DES key.
    --Kevin

Maybe you are looking for

  • Custom font not exported in PDF

    Hello Guys, In my web application, I have a crystal report developed in CR11 R2 SP3. The report uses custom font and it works fine when shown in report viewer. However I get errors while exporting report as PDF. 1) In windows 2003 server, the pdf is

  • All my notes have been deleted and I can't get them back

    M-My notes had doubled so. Deleted the doubled up notes when I went on the app late they had all dissapeared my phine and ipad have since synced with icloud again is thee anyway of retrieving them I am desperate

  • Why does'nt refresh UIX page after executeQuery?

    I have UIX page and DCIteratorBinding iter = actionContext.getBindingContainer().findIteratorBinding("PrcCalendarsView2Iterator"); iter.executeQuery(); executeQuery method in prepareModel but UIX page dos'ent refresh why?

  • Function for Date Validation

    Hi, Can anyone tell me a Function Module to Valdate Date? Thanks & Regards Sheela

  • Base unit change

    Dear sir Material have already movement that material comes to stock & account hit, later due to some reason we want to change base unit of measure in material master record , please guide me how to do it ? Regards Mahesh