0

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

G M Ramesh
  • 3,420
  • 9
  • 37
  • 53

4 Answers4

3

Split the String by comma into String array and parse it to Byte.

        String s = "82,73,70,70,90,95,3,0,87,65,86";
        String[] splitedStr = s.split(",");
        byte[] b = new byte[split.length];
        int i=0;
        for (String byt : splitedStr) {
                 try{
            b[i++]=Byte.parseByte(byt);
                 }catch(Exception ex){ex.printStackTrace();}
        }
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
3

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

Community
  • 1
  • 1
Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106
1
String.split(",")

returns an array of strings containing your single numbers.

Byte.parse()

parses your string to byte values. Iterate in a loop over all elements an fill your byte array.

Bondax
  • 3,143
  • 28
  • 35
0

# How to convert String to byteArray and byteArray to String Array in java?#

String passwordValue="pass1234";

        SharedPreferences sharedPreferences;

        SharedPreferences.Editor editor;

        sharedPreferences = getActivity.getSharedPreferences("key",Context.MODE_PRIVATE);

        editor = sharedPreferences.edit();

        byte[] password = Base64.encode(passwordValue.getBytes(), Base64.DEFAULT);

        editor.putString("password", Arrays.toString(password));

        editor.commit();

        String password = sharedPreferences.getString("password", "");

        if (password != null) {

        String[] split = password.substring(1, password.length()-1).split(", ");

        byte[] array = new byte[split.length];

        for (int i = 0; i < split.length; i++) {

        array[i] = Byte.parseByte(split[i]);

        }

        byte[] decodeValue = Base64.decode(array, Base64.DEFAULT);

        userName.setText("" + new String(decodeValue));

        }  
        Output:-

        password:-"pass1234"  

        Encoded:-password: 0 = 99
        1 = 71
        2 = 70
        3 = 122
        4 = 99
        5 = 122
        6 = 69
        7 = 121
        8 = 77
        9 = 122
        10 = 81
        11 = 61
        12 = 10

        Decoded password:-pass1234 
Ashutosh Srivastava
  • 597
  • 1
  • 9
  • 13