• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Array of Bytes to String and String to Array of Bytes

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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();
}
}
}
 
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic