繁体   English   中英

如何在Java中将String转换为byteArray并将byteArray转换为String Array?

[英]How to convert String to byteArray and byteArray to String Array in java?

我想在Java中将String转换为bytearray。

例如我想输出如下:

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

现在的逻辑是,我想要字节数组值中的相同String值,例如

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

b = s.getBytes(); 不返回相同的值...它返回字节数组值的每个字符串

任何帮助将不胜感激

拆分String用逗号成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>); 解析每个数字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()

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

如何在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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM