String & byte

Hello everybody,
I'm in this situation: I have a byte array initialized by a list of integers. For some reason, my goal is to convert it to a String and then to get those integers.
I wrote this simple code:
byte b[] = { -38, -127, -53, -52, 87, 40, -50, -44, -53, 87, -56, -52, 63, 81, 0, -56, 76, -84, 2, 0, 43, -120, 5, -5 };
String s = new String(b);
byte b2[] = s.getBytes();
for(int i=0; i<b2.length; i++)
System.out.println((int)(b2));
but, it works with all ingers except -127, in facts it displays -127 as 63!
How can I solve this problem? Thanks!

BalusC wrote:
I tried ISO-8859-1 here and it worked.
byte[] bytes = { -38, -127, -53, -52, 87, 40, -50, -44, -53, 87, -56, -52, 63, 81, 0, -56, 76, -84, 2, 0, 43, -120, 5, -5 };
String string = new String(bytes, "ISO-8859-1");
for (byte b : string.getBytes("ISO-8859-1")) {
System.out.print(b + " ");
All the ISOs 'work' but the point is - what it the OP trying to do?

Similar Messages

  • Memory leak in String(byte[] bytes, int offset, int length)

    Has anyone run into memory leak problem using this String(byte[] bytes, int offset, int length) class? I am using it to convert byte array to string, and I am showing memory leak using this class. Any idea what is going on?

    Hi,
    If you post in Native methods forum I assume you are using this constructor in the native side.
    Be aware that getting char * from jstring eats memory that you must free before returning from native with env->ReleaseStringUTFChars().
    --Marc (http://jnative.sf.net)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • String.getBytes() & String(byte[]) - java.nio.BufferOverflowException

    The application in question uses JNI for legacy integration and I suspect the legacy code is corrupting the stack causing the above error. However, the error does not occur in Java 1.3, only Java 1.4.
    Is there some way to suppress 1.4's use of the native IO API when encoding and decoding byte streams? This would at least provide a workaround in the meantime.
    Thanks.

    This is beginning to make a little sense. The problem is that you got a String and you don't want one. A String wraps an array of chars, which your app needs, right? Specifically they're chars because you need 16-bit char sets.
    Presumably the getBytes() method call is used to get an array of bytes for some data transfer operation. java.nio was probably added in 1.4 as it has some very efficient ways of handling buffers as simultaneously of two or more types. It's trying to use the underlying char array as a byte array and there's a straight up bug someplace.
    Workaround is strange to contemplate, but I'm pretty sure it will work: use String.getChars() to get an array of chars, and then use java.nio yourself to create your byte array! If you've never been there, it's not very hard. I use nio all the time and it's never been a problem.

  • Strings, byte[]s, and encoding ....

    I'm realising I really don't know anything of the java encoding fonctionnalities ...
    For example: I' ve written amethod String encode(String) which transforms a bytecode (I hope parameter's byecode) in an other bytecode (I hope result's bytecoed). This transformation is done with a special Charset that I've built. And I use Charset.encode(String).
    I've try to call this method with two String parameters. These two String give the same result when calling System.out.println(....) and String.getBytes(). But the two results of my method's call with these two parameters are different !!!!!! How is it possible ?????
    There a lot of things I don't know. For example:
    - how many bytes are needed to encode an ISO-8859-1 (default java encoding) or UTF-8 character ?
    - How can I get the real bytecode of a String, I mean the bytecodes of all its characters ? (for example if a String contains 4 characters, its real bytecode should contain 8 bytes)
    Thank's for any help.

    I've try to call this method with two String
    parameters. These two String give the same result when
    calling System.out.println(....) and
    String.getBytes(). But the two results of my method's
    call with these two parameters are different !!!!!!
    How is it possible ?????You used getBytes(String charsetName) with a set of characters that included both overlapping and non-overlapping characters?

  • Hex code string -- byte array

    hi everyone,
    i have a bunch of hexadecimal code which is read from a text file into a String.
    i want to put this String into a byte array without changing anything.
    my algorithm is like this -
    String strFromTextFile = "FFD8FFE0001";
    * put strFromTextFile into byteArr[ ]
    byteArr[0] == 'F';
    byteArr[1] == 'F';
    byteArr[2] == 'D';

    hi, i think this simple code will fulfill ur need
    public class hex {
         public static void main(String[] args) {
              String str= "AFFD8FFE0001";
              byte hexbytes[] =     hexstore(str);
    public     static byte[] hexstore(String str)
          int length = str.length();
          if((length%2)!=0)
               length++;
               str = new String(str+"0");
          byte[] a = new byte[length/2];
          for(int i=0,j=0;i<str.length();i=i+2,j++)
              byte c =(byte) str.charAt(i);     
              if(c<65)
                   c= (byte)((int)c-48);               
              else
                   c= (byte)(10+(int)c-65);
                   c=(byte)((int)c<<4);
              byte d =(byte) str.charAt(i+1);
              if(d<65)
                   d= (byte)((int)d-48);               
              else
                   d= (byte)(10+(int)d-65);
                   c = (byte)(c | d);
                   a[j]=c;
              for(int i=0;i<length/2;i++)
                   System.out.println("byte "+((int)a));
              return a;
    example ( for first 2 characters)
    AF has to be stored as 1010 1111
    1010 1111 is stoted in a[0];

  • Simple string / bytes problem

    Hi
    I'm basically trying to simulate DES in java from scratch (so no use of existing API's or anything). I've got a basic idea of how DES works (use of a feistel cipher).
    So to start off I'm trying to get the bytes of a string with this simple program:
    public class Test {
         public static void main(String[] args) {     
              String testString = "hello";
              System.out.println(testString.getBytes());
    }The output consists of some characters (namely numbers, letters and 1 special character).
    But when I change the variable testString to some other String, complie and run I still get the same output even though the String is different. Also why are there 9 characters for a String thats only 5 characters long?
    Thanks

    When you use System.out.println( something ) it uses to the toString() method of the object referenced by 'something'. When the something is an array such as an array of bytes the toString() methed returns a pseudo reference to the array which in no way reflects the content of the array.
    If you just want to see the content of the array then use Arrays.toString(something) to generate a String representation of the content of the array.
    Also, the use of String.getBytes() will convert the String to bytes using your default character encoding. This is rarely what you want since the result may depend on which platform you are working on. In my view, the safest and best approach is to explicitly define the encoding and since it will encode ALL characters one can throw at it I always use utf-8. So, to convert a String to bytes I would usebyte[] bytesOfString = "your string".getBytes("utf-8");and to convert them back to a String I would useString yourString = new String(bytesOfString,"utf-8");One final point, do not assume that an apparently random array of bytes such as one gets from DES encryption can be converted to a String using the above. In general it can't because not all bytes and byte sequences are valid for a particular character encoding. If you absolutely have to have a String representation then you should encode (not encrypt) the bytes using something like Base64 or Hex encoding.
    Edited by: sabre150 on Jan 27, 2008 3:04 PM

  • New String(byte[]) taking up huge space?

    Ok. I have a byte[] of approx. 5.000.000 bytes. Whenever, at any point, I try to create a String using this array by new String(array), my memoryusage increases by about 60/65 megabytes. Can anyone please explain me why on earth it's doing this?
    Note also that this space is not freed up by the GC (afterwards).
    Thanks in advance

    Actually, I've discovered some details about the swing textcomponents. They're very bad for 'simply' showing 2mb+ files.
    Check out these bugs; original and "more recent".
    It doesn't quite explain why putting a byte array to a string occupies twice the space, but it does seem to account for the huge memory increase when putting it to a JTextArea.
    String is immutable so it has to copy your char[] to
    a new char[] backing the String. If it used theSure thing, but I'm passing on a byte[] array, and afaik, it's not using this array and should only copy it. Once.
    Oh hey, could it be that the bytes are saved in unicode? That would double the size... and make sense...
    Oh and PS; Maybe you should read this if you really think strings are immutable... (although you are generally correct :))

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

  • 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

  • String and stringtokenizer problem

    Hi,
    String s=new String(null);
    is it possible or not?
    StringTokenizer st=new StringTokenizer(null,",");
    is it possible or not?

    hi sudha,
    when u write
    String s=new String(null); is wrong. Just b'coz the method of String(byte()) that are from java.lang.String will match with your declared method.
    so it will have to clashing ...so u will get ERROR dear.
    Regards
    saM

  • How to convert BLOB into a String

    Hi,
    I got a blob column from the database.
    It contains one XML File.
    How to convert it into String.
    I need the code for how to convert the blob into String
    Thanks in Advance.

    A blob would be a byte-array, which you can use in the String(byte[]) constructor

  • String deprecation

    I have a warning when compiling a jdk1.1 file under j2sdk1.4
    the String(byte[],int)has been deprecated and I didn't understand how to change the instruction using string constructors as it is said in the note in the documentation.
    please tell me how.
    thanks

    If you look at the Documentation for String:
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/String.html#constructor_summary
    It says:
    String(byte[] ascii, int hibyte)
    Deprecated. This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do this is via the String constructors that take a charset name or that use the platform's default charset.
    And here is that constructor
    String(byte[] bytes, String charsetName)
    Constructs a new String by decoding the specified array of bytes using the specified charset.
    You can start with this "ISO-8859-1" as charsetName, then look here is you want something different.
    http://java.sun.com/j2se/1.3/docs/api/java/lang/package-summary.html#charenc

  • How to save a value in a byte array, retrieve it and display it?

    Hi,
    I am doing a project for my data structures class that involves saving a value (given in String format) in a byte array (our 'memory'). Initially I just tried casting character by character into the byte array and casting back to char[] for retrieval (using .toString() to return what's supposed to be the original string), but this did not work. I tried the .getBytes() method, applying it to the string and then trying to recover it by placing the contents of the 'memory' in a byte array and applying toString(), but that didn't work either. I looked a bit and found this class, CharsetEncoder and CharsetDecoder. I tried to use these but when I try the compiler tells me I cannot instantiate CharsetDecoder because it is an abstract class. At this point I'm at a loss as to what I can do. Is there any way to place a string in a byte array and then recover the string in it's original format? For example, I might save a value in my particular class of "456". But when I try to recover the value from my 'memory' i.e. the byte array, it comes out like [gnue@hnju.... or something similar. I need it to output the original string ("456").
    Below is my code as it is right now, for the methods setValue and getValue.
    Thanks!
    public void setValue(String value) throws InvalidValueException {
         //… stores the given value in the memory area assigned to the variable
              if(this.type.isValidValue(value)){
                   bytes = value.getBytes();
                   int i,j,k;
                   int l=0;//might be wrong?
                   int ad=address-(address%4);
                   mem.readWord(ad);
                   reg=mem.getDataRegister();
                   if((address%4)+bytes.length-1<4){
                        for(i=address%4;i<address%4+bytes.length;i++)
                             reg.setByte(i, bytes[i]);
                        mem.setDataRegister(reg);
                        mem.writeWord(ad);
                   else if((address%4)+bytes.length-1>=4){
                        if(address%4!=0){
                             for(i=address%4;i<4;i++){
                                  reg.setByte(i, bytes);
                                  l++;
                             mem.setDataRegister(reg);
                             mem.writeWord(ad);
                             ad+=mem.WORDSIZE;
                        while(ad<address+bytes.length-(address+bytes.length)%4){
                             for(j=0;j<4;j++){
                                  reg.setByte(j, bytes[j+l]);
                                  l++;
                             mem.setDataRegister(reg);
                             mem.writeWord(ad);
                             ad+=mem.WORDSIZE;
                        if((address+bytes.length)%4!=0){
                             mem.readWord(ad);
                             reg=mem.getDataRegister();
                             for(k=0;k<(address+bytes.length)%4;k++){
                                  reg.setByte(k, bytes[k+l]);
                                  l++;
                             mem.setDataRegister(reg);
                             mem.writeWord(ad);
                   else
                        throw new InvalidValueException("The value passed is not valid.");
         /** Gets the current value of the variable.
         @return current value converted to String
         public String getValue() {
              //… returns the current value stored in the corresponding memory area
              //… value is converted to String
              bytes=new byte[this.getType().getSize()];
              int i,j,k;
              int l=0;//might be wrong?
              int ad=address-(address%4);
              mem.readWord(ad);
              reg=mem.getDataRegister();
              if((address%4)+bytes.length-1<4){
                   for(i=address%4;i<address%4+bytes.length;i++)
                        bytes[i] = reg.readByte(i);
              else if((address%4)+bytes.length-1>=4){
                   if(address%4!=0){
                        for(i=address%4;i<4;i++){
                             bytes[i] = reg.readByte(i);
                             l++;
                        ad+=mem.WORDSIZE;
                   mem.readWord(ad);
                   reg=mem.getDataRegister();
                   while(ad<address+bytes.length-(address+bytes.length)%4){
                        for(j=0;j<4;j++){
                             bytes[j+l] = reg.readByte(j);
                             l++;
                        ad+=mem.WORDSIZE;
                   if((address+bytes.length)%4!=0){
                        mem.readWord(ad);
                        reg=mem.getDataRegister();
                        for(k=0;k<(address+bytes.length)%4;k++){
                             bytes[k+l] = reg.readByte(k);
                             l++;
              return bytes.toString();

    You can certainly put it into a byte array and then construct a new String from that byte array. Just calling toString doesn't mean you'll automatically get a meaningful string out of it. Arrays do not override the toString method, so the use the one inherited from object.
    Look at String's constructors.

  • JCO.Server appends null character to string

    I am a complete SAP and JCO newbie so I'll try making as much since as I can, given the fact that I'm not familiar with SAP terminology and technology. I've been lent as a developer to another group which needs a legacy application rewritten. The application processes a RFC and decrypts the RFC encrypted payload and returns it along with a status code.
    I have made progress - I'm able to register my server with the SAP runtime and using the SAP GUI application and the help of a SAP developer, I'm able to make an RFC call to my application. I'm able to read the parameters sent from SAP and write parameters back.
    The problem is that one of the parameters I'm writing back (java.lang.String) appears to have and extra character on SAP side. On the GUI it appears as a '#' (pound) sign. The SAP developer told me the string is terminated with a null character which I know is a C/C++ thing but not a Java thing. I don't think it is a Unicode issue. The Java server is not running in Unicode mode and any attempt to set the jco.server.unicode property (I may have forgotten the exact name) to a value of 1 causes the RFC to fail.
    I think the issue is likely to be the manner in which I defined the function parameters or the manner in which I write them. The following are code snippets:
    Defining the function:
    JCO.MetaData metadata = new JCO.MetaData(Constants.FUNCTION_DECRYPT);
    metadata.addInfo(Constants.PARAMETER_SCHEME,      JCO.TYPE_INT,    255,   0,  0, JCO.IMPORT_PARAMETER, null);
    metadata.addInfo(Constants.PARAMETER_ENCRYPTED,   JCO.TYPE_STRING, 255,   0,  0, JCO.IMPORT_PARAMETER, null);
    metadata.addInfo(Constants.PARAMETER_DECRYPTED,   JCO.TYPE_STRING, 255,   0,  0, JCO.EXPORT_PARAMETER, null);
    metadata.addInfo(Constants.PARAMETER_RETURN_CODE, JCO.TYPE_INT,    255,   0,  0, JCO.EXPORT_PARAMETER, null);
    Server request handling code:
    protected void handleRequest(JCO.Function function)
                    // Obtaining import/export parameter lists.
                    JCO.ParameterList input  = function.getImportParameterList();
                    JCO.ParameterList output = function.getExportParameterList();
                    // Getting scheme and encrypted text parameters.
                    int scheme       = input.getInt(Constants.PARAMETER_SCHEME);
                    String encrypted = input.getString(Constants.PARAMETER_ENCRYPTED);
                    // Decoding base 64 string.
                    byte[] bytes = Base64.decode(encrypted);
                    // Obtaining cipher by scheme and decrypting the text.
                    AppCipher cipher = ApplicationConfiguration.getDecryptor(scheme);
                    if(cipher == null)
                                    logger.error("Unable to get cipher due to an unknown encryption scheme: " + scheme);
                    else
                                    byte[] decrypted = cipher.decrypt(bytes);
                                    String plainText = new String(decrypted);
                                    // Setting decrypted value information and return code.
                                    output.setValue(plainText, Constants.PARAMETER_DECRYPTED);
                                    output.setValue(Constants.RETURN_CODE_SUCCESS, Constants.PARAMETER_RETURN_CODE);

    I seem to have made progress. If I define the parameter type as JCO.TYPE_CHAR instead of JCO.TYPE_STRING, it works:
    metadata.addInfo(Constants.PARAMETER_DECRYPTED,   JCO.TYPE_CHAR,   255,   0,  0, JCO.EXPORT_PARAMETER, null);
    That is the only change I made. I'm still setting the parameter value as java.lang.String. I hope this won't cause issues elsewhere. I was also able to change the field definition and set it as a byte array. However, that had the problem of having to define the exact length of the byte array in the field metadata otherwise the remaining bytes would appear as null bytes on SAP side.

  • Convery byte[] into a object

    i have a byte[] which I have got from DB. I want to convert it into a object before returning it from a method. There is a wraaper class for byte i.e. Byte. But I am not sure tha how to convert a byte[] into an Object.
    Thanks!!

    georgexu316 wrote:
    corlettk wrote:
    georgexu316 wrote:
    If you know what you are doing, you can perform an implicit conversion by casting the byte.
    byte byteData = new byte();
    Object newObj = (Object) byteData;
    Umm.. Dude, a byte array is-an Object. In Java you don't ever need to explicitly up-cast... but (in order to actually use it as a byte array) you do have to explicitly down-cast it.
    For example:
    package forums;
    class AByteArrayIsAnObject
    public static void main(String[] args) {
    try {
    Object bytes = "Hello World!".getBytes(); // returns a reference to a newly created byte-array-object
    System.out.println( new String((byte[])bytes) );
    } catch (Exception e) {
    e.printStackTrace();
    Well, the person asked to convert it into an Object, maybe he needs it as a object to pass it through another parameter of another method. Even though byte is an extension of Object and you can use all of Object's methods, it wouldn't pass through a parameter of a method that specifies an object.Ummm... Wanna bet?
    package forums;
    class AByteArrayIsAnObjectTest
      public static void main(String[] args) {
        try {
          println(new String((byte[])getBytes("Hello World!")));
        } catch (Exception e) {
          e.printStackTrace();
      private static Object getBytes(String s) {
        return s.getBytes();
      private static void println(Object o) {
        System.out.println(String.valueOf(o));
    }

Maybe you are looking for