我想在java中将String转换为bytearray ..
例如,我想要如下输出:
String s = "82,73,70,70,90,95,3,0,87,65,86";
现在的逻辑是,我想要 bytearray 值中的相同字符串值,例如
byte[] b ={82,73,70,70,90,95,3,0,87,65,86};
b = s.getBytes();
不返回相同的值...它返回字节数组值的每个字符串
任何帮助将不胜感激
String
将by 逗号拆分String array
为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();}
}
所以你可以尝试拆分你String
的,
,然后在循环中用静态方法解析每个数字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++;
}
也有看看
String.split(",")
返回一个包含单个数字的字符串数组。
Byte.parse()
将您的字符串解析为字节值。循环遍历所有元素并填充您的字节数组。
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