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?

Similar Messages

  • How to convert byte into string

    can any tell me how to convert byte into string
    when im an debugging thid code in eclipse it shows the result in integer format instead of string but in command prompt it is showing result in string format..........plz help
    package str;
    import java.io.*;
    public class Testfile {
    public static void main(String rags[])
    byte b[]=new byte[100];
    try{
    FileInputStream file=new FileInputStream("abc.txt");
    file.read(b,0,50);
    catch(Exception e)
         System.out.println("Exception is:"+e);
    System.out.println(b);
    String str=new String(b);
    System.out.println(str);
    }

    Namrata.Kakkar wrote:
    errors: count cannot be resolved and Unhandled exception type Unsupported Encoding Exception.
    If i write an integer value instead of "count" then Unhandled exception type Unsupported Encoding Exception error is left.This is elementary. You need to go back to [http://java.sun.com/docs/books/tutorial/|http://java.sun.com/docs/books/tutorial/] .

  • 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 bytes to strings

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

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

  • How do I convert 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.

  • Conversion of byte into string

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

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

  • How to 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

  • Help with Sample on Converting an XML string to a byte stream

    Hello All,<br /><br />I am sure this is something simple, but I am just not figuring it out right now.<br /><br />I am following the sample - "Converting an XML string to a byte stream" from the developer guide since I want to prepopulate just 1 field in my PDF form.<br /><br />How do I reference my form field within my servlet code properly??<br /><br />I have tried a few things now, my field is within a subform, so I thought it would be <root><subformName><fieldname>My data</fieldname></subformName></root>  I have also tried adding <page1> in there too.<br /><br />I am following everything else exactly as given in the sample code.<br /><br />I do have an embedded schema within the form and the field is bound.<br /><br />Thanks,<br />Jennifer

    Well, if you have a schema defined in the form, then the hierarchy of your data must match what is described in the schema. So, can't really tell you what it would look like, but just follow your schema.
    Chris
    Adobe Enterprise Developer Support

  • 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

  • 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

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

  • Converting from spreadshet string to array and then back to spreadsheet string

    My questions is; why is the Spreadsheet string to array function creating more data than the original string had when you change the array back into a spreadsheet string. Im trying to analyze a comma delimited file using array functions since my column and row size is constant, but my data varies. Thus my reason for not using string parsing functions which would get more involved and difficult. So, however, after i convert to a 2D array of data from the comma delimited file I read from, and then I convert back to string using the Array to Spreadsheet String, I get added columns to the file, which prevents another program from receiving these files. Also, the data which I am reading is not all contiguous, it has gaps in some places for empty data. Looking at the file compared to the original after it has gone from string to array and then back to string again, looks almost identical except for the file size which got larger by 400 bytes and where the original file has empty spaces, the new file has a lot of commas added. Any idea?
    Charles

    The result you get is normal when the spreadsheet string contains rows of uneven length. Since the array rows have the same number of elements, nil values are added during the coonversion. And of course, the back to string conversion keep those added values in the string, with the associated commas.
    example : 3 x 3 array
    1,2,3
    4
    5,6,7
    is converted into
    1 2 3
    4 0 0
    5 6 7
    then back to
    1,2,3
    4,0,0
    5,6,7
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        

  • How to convert bytes to GB inside of a text file

    I'm using a PS script to automate WSUS cleanup and then output the results to a text file which is then emailed to me.
    The output for Diskspace Freed is displayed in bytes, I would like to convert this to GB, but I am having trouble getting this to work.
    Here is what I was attempting to work with, but it is not working properly (the 2nd line). 
    Get-WsusServer | Invoke-WsusServerCleanup -CleanupObsoleteUpdates -CleanupUnneededContentFiles | Out-File "C:\Users\USER1\Downloads\WSUS Cleanup Log\cleanup $(get-date -f MM-dd-yy).txt"
    #(Get-Content "C:\Users\USER1\Downloads\WSUS Cleanup Log\cleanup $(get-date -f MM-dd-yy).txt") | ForEach-Object {$_."diskspace free" / 1MB} | Set-Content "C:\Users\USER1\Downloads\WSUS Cleanup Log\cleanup $(get-date -f MM-dd-yy).txt""C:\WSUS PS Script\cleanup $(get-date -f MM-dd-yy).txt"
    Send-MailMessage -to [email protected] -Subject "WSUS Cleanup" -Attachments "C:\Users\USER1\Downloads\WSUS Cleanup Log\cleanup $(get-date -f MM-dd-yy).txt" -SmtpServer 192.X.X.X -from [email protected]

    Hi Granite,
    I've got to guess here - don't have a handy 2012R2 Wsus Server at hand and I'm extrapolating from the Technet Library's documentation example output for Invoke-WsusServerCleanup - but this is what I came up with:
    $File = "C:\Users\USER1\Downloads\WSUS Cleanup Log\cleanup $(get-date -f MM-dd-yy).txt"
    $Script = {
    if ($_ -match "diskspace free")
    $Bytes = ($_.Trim().Split(":") | Select -Last 1).Trim()
    $String = ($_.Trim().Split(":") | Select -First 1).Trim() + ": "
    $String += "{0:n3}" -f ($Bytes / 1GB)
    $String += "GB"
    $String
    else { $_ }
    Get-WsusServer | Invoke-WsusServerCleanup -CleanupObsoleteUpdates -CleanupUnneededContentFiles | ForEach-Object $script | Out-File $File
    Send-MailMessage -to [email protected] -Subject "WSUS Cleanup" -Attachments $File -SmtpServer 192.X.X.X -from [email protected]
    If this doesn't work out for you, please post the actual output of the Cleanup Command.
    Cheers,
    Fred
    There's no place like 127.0.0.1
    Thanks for the response, this is exactly what I was looking for!
    The script ran with no errors. The output does show as GB, however since the script was already ran today there value is currently 0. I will test this again in a couple of days.

Maybe you are looking for