How to convert String to byteArray and byteArray to String Array in Java?

advertisements

I want to convert String to bytearray in java..

For Example i want output like the following :

String s = "82,73,70,70,90,95,3,0,87,65,86";

Now the logic is , i want same String value in bytearray value like

byte[] b ={82,73,70,70,90,95,3,0,87,65,86};

b = s.getBytes(); doesn't return the same value...it returns each string of byte array value

Any help would be appreciated lot


So you can try to split your String with , and then in loop parse each number with static method Byte.parseByte(<el>);

String source = "1,2,3,4,5";
String[] temp = source.split(","); // this split your String with ,
byte[] bytesArray = new byte[temp.lenght];
int index = 0;
for (String item: temp) {
   bytesArray[index] = Byte.parseByte(item);
   index++;
}

Also have look at