wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Array of Bytes to String and String to Array of  Bytes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array of Bytes to String and String to Array of  Bytes" Watch "Array of Bytes to String and String to Array of  Bytes" New topic
Author

Array of Bytes to String and String to Array of Bytes

Rakesh kumar
Greenhorn

Joined: Oct 09, 2003
Posts: 1
I have an array of bytes. I get a string using US-ASCII encoding. Now I try to get the array of bytes from the resulting String using US-ASCII encoding. I expect the original array of bytes. However I am not getting it. Any clue? See the code below :
public class ByteToString
{
public static void main(String[] args)
{
try{

byte[] b = { -48 , -71 , -62 };
String s = new String( b, "US-ASCII");
System.out.println("String1 =" + s);
byte[] c = s.getBytes( "US-ASCII");
for( int i = 0 ; i < c.length ; ++i )
{
System.out.println( "C=" +c[i] );
}


}
catch( Exception e)
{
System.out.println( "error: " + e.getMessage() );
e.printStackTrace();
}
}
}
Arun Boraiah
Ranch Hand

Joined: Nov 28, 2001
Posts: 233
All your bit value are negative value.
In your case when byte array is converted to string it is converted to ASCII equivalent of it i.e. 65 = A 66 =B etc since
Negative value is not having any equivalent ASCII you can see change in this value. Check it out by converting your value to positive integer.


Sharing is learning
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Array of Bytes to String and String to Array of Bytes
 
Similar Threads
byte array question
javax.crypto.BadPaddingException: Given final block not properly padded
Encoding and Decoding Issues across OS
URLyBird: about read the records from the database file.
ascii decimal conversion problem