0

我想在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();不返回相同的值...它返回字节数组值的每个字符串

任何帮助将不胜感激

4

4 回答 4

3

String将by 逗号拆分String arrayByte.

        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();}
        }
于 2012-11-06T07:22:37.070 回答
3

所以你可以尝试拆分你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++;
}

也有看看

于 2012-11-06T07:24:46.307 回答
1
String.split(",")

返回一个包含单个数字的字符串数组。

Byte.parse()

将您的字符串解析为字节值。循环遍历所有元素并填充您的字节数组。

于 2012-11-06T07:22:01.803 回答
0

# 如何在 java 中将 String 转换为 byteArray 和 byteArray 到 String 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 
于 2016-12-27T13:02:17.340 回答