如何将字节数组转换为字符串,反之亦然? [英] How to convert byte array to string and vice versa?
问题描述
我必须在Android中将字节数组转换为字符串,但我的字节数组包含负值。
I have to convert a byte array to string in Android, but my byte array contains negative values.
如果我将该字符串再次转换为字节数组,则值为I我得到的是与原始字节数组值不同。
If I convert that string again to byte array, values I am getting are different from original byte array values.
我可以做些什么来获得正确的转换?我用来进行转换的代码如下:
What can I do to get proper conversion? Code I am using to do the conversion is as follows:
// Code to convert byte arr to str:
byte[] by_original = {0,1,-2,3,-4,-5,6};
String str1 = new String(by_original);
System.out.println("str1 >> "+str1);
// Code to convert str to byte arr:
byte[] by_new = str1.getBytes();
for(int i=0;i<by_new.length;i++)
System.out.println("by1["+i+"] >> "+str1);
我遇到了这个问题。
推荐答案
您的字节数组必须有一些编码。如果您有负值,则编码不能是ASCII。一旦弄明白,就可以使用以下命令将一组字节转换为字符串:
Your byte array must have some encoding. The encoding cannot be ASCII if you've got negative values. Once you figure that out, you can convert a set of bytes to a String using:
byte[] bytes = {...}
String str = new String(bytes, "UTF-8"); // for UTF-8 encoding
您可以使用一堆编码,查看Charset Sun javadocs 中的类。
There are a bunch of encodings you can use, look at the Charset class in the Sun javadocs.
这篇关于如何将字节数组转换为字符串,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!