Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array of Bytes to String and String to Array of Bytes

 
Rakesh kumar
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 233
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic