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
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();}
}
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
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.