2012-11-06 105 views
0

我要转换的字符串在Java字节组到..如何将字符串转换为byteArray和字节数组在Java中的字符串数组?

例如,我想像的输出如下:

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

现在逻辑,我想像

在字节组值相同的字符串值
byte[] b ={82,73,70,70,90,95,3,0,87,65,86}; 

b = s.getBytes();不返回相同的值...返回字节数组值

任何帮助的每串将不胜感激

+1

输入值有多大范围?整数的最小和最大可能值是多少? –

+0

值的范围将在2048或4096左右 –

回答

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++; 
} 

也有看

+0

非常感谢你 –

+0

欢迎光临:) – Sajmon

1
String.split(",") 

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

Byte.parse() 

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

3

将逗号分割为StringString 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();} 
     } 
+0

非常感谢你,它工作 –

0

如何将字符串转换为byteArray和字节数组在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 
相关问题