Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

byte Array to String and String to byte Array

843810Oct 2 2003 — edited Oct 3 2003
First of all Thank You in Advance.

I am converting a byte array to String and then convert same String to byte array. If my byte array contain these values (-127,-115,-113,-112,-99) then the output will not correct why? and tell me why all these element encoded to 63.

take a look a this program only for five number Test.

public class TestBytes
{
public static void main(String args[])
{
byte b[] = {-127,-115,-113,-112,-99,-11,65,66}; /* initialize a byte array b. */
String s = new String(b); /* convert byte array b to String s. */
byte a[] = s.getBytes();
/* reverse the process i.e convert String s to byte array a and then contents of byte array a must equal to contents of byte array b. */
System.out.println(s); // String Contents
for(int i = 0 ; i < a.length ; i++)
{
System.out.print(a [ i ] + ",");
/* but the contents of byte array a are: 63,63,63,63,63,-11,65,66, */
}
}
}

Same Program But Cover All the 256 elements -128 to 127

public class TestBytes
{
public static void main(String args[])
{
byte b[] = new byte[256];
for(int i = -128,j = 0 ; i < 128 && j < 256 ; i++,j++)
{
b [ j++ ] = (byte)i; /* fill the byte array with -128 to +127*/
}
String s = new String(b); /* convert byte array b to String s. */
byte a[] = s.getBytes(); /* reverse the process i.e convert String s to byte array a and then contents of byte array a must equal to contents of byte array b. */
s = ""; /* empty the String s */
for(int i = 0 ; i < a.length ; i++)
{

/* Now compare hole array it will compare all numbers(-128 to +127) but these five (-127,-115,-113,-112,-99) will be replaced by 63 '?'. why these numbers can not converted, means convert all negative numbers except these (-127,-115,-113,-112,-99). what is the problem with these numbers.*/

if(a[ i ] != b[ i ])
{
s += "" + a[ i ] + " , " + b[ i ] + " \n\n";
/* a is converted array and b is orignal array*/
}
}
System.out.println(s);
}
}

Basically I am developing Encryption/Decryption program which will apply to any file. so I am reading a File(txt,doc,jpg or etc.) Using FileInputStream class, after reading the all the data is in byte array. I will convert it to String, to apply my Encryption algoritm on it. After this i am converting Encrypted String to byte array to write the data in file using FileOutputStream class.
Decrption Process is just reverse of above process that why i need to convert a byte array to String and vice versa.

Yahya Kamran.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 31 2003
Added on Oct 2 2003
1 comment
2,151 views