我必须将字节数组转换为Android中的字符串,但我的字节数组包含负值。

如果我将该字符串再次转换为字节数组,我得到的值与原始字节数组值不同。

我该怎么做才能得到正确的转换?我用来做转换的代码如下:

// 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);

我被这个问题难住了。


当前回答

下面是示例代码,可以安全地将字节数组转换为字符串,并将字符串转换为字节数组。

 byte bytesArray[] = { 1, -2, 4, -5, 10};
 String encoded = java.util.Base64.getEncoder().encodeToString(bytesArray);
 byte[] decoded = java.util.Base64.getDecoder().decode(encoded);
 System.out.println("input: "+Arrays.toString(bytesArray));
 System.out.println("encoded: "+encoded);
 System.out.println("decoded: "+Arrays.toString(decoded));

输出:

input: [1, -2, 4, -5, 10]
encoded: Af4E+wo=
decoded: [1, -2, 4, -5, 10]

其他回答

使用new String(byOriginal)并使用getBytes()转换回byte[]并不能保证两个byte[]具有相等的值。这是因为调用了StringCoding.encode(..),它会将String编码为Charset.defaultCharset()。在这种编码过程中,编码器可能会选择替换未知字符并进行其他更改。因此,使用String.getBytes()可能不会返回最初传递给构造函数的相等数组。

我确实注意到了一些答案里没有的东西。可以将字节数组中的每个字节强制转换为字符,并将它们放入字符数组中。然后字符串是new string (cbuf),其中cbuf是char数组。要进行反向转换,需要循环将每个字符转换为字节,然后放入字节数组中,这个字节数组将与第一个字节数组相同。


public class StringByteArrTest {

    public static void main(String[] args) {
        // put whatever byte array here
        byte[] arr = new byte[] {-12, -100, -49, 100, -63, 0, -90};
        for (byte b: arr) System.out.println(b);
        // put data into this char array
        char[] cbuf = new char[arr.length];
        for (int i = 0; i < arr.length; i++) {
            cbuf[i] = (char) arr[i];
        }
        // this is the string
        String s = new String(cbuf);
        System.out.println(s);

        // converting back
        byte[] out = new byte[s.length()];
        for (int i = 0; i < s.length(); i++) {
            out[i] = (byte) s.charAt(i);
        }
        for (byte b: out) System.out.println(b);
    }

}

这个对我来说适用于android Q:

您可以使用以下方法将十六进制字符串转换为字符串

    public static String hexToString(String hex) {
    StringBuilder sb = new StringBuilder();
    char[] hexData = hex.toCharArray();
    for (int count = 0; count < hexData.length - 1; count += 2) {
        int firstDigit = Character.digit(hexData[count], 16);
        int lastDigit = Character.digit(hexData[count + 1], 16);
        int decimal = firstDigit * 16 + lastDigit;
        sb.append((char)decimal);
    }
    return sb.toString();
}

将字节数组转换为十六进制字符串

    public static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for (int j = 0; j < bytes.length; j++) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

尽管

new String(bytes, "UTF-8")

如果是正确的,它会抛出一个UnsupportedEncodingException,迫使你处理一个checked异常。你可以使用自Java 1.6以来的另一个构造函数来将字节数组转换为String:

new String(bytes, StandardCharsets.UTF_8)

这个函数不会抛出任何异常。

转换回也应该用StandardCharsets完成。UTF_8:

"test".getBytes(StandardCharsets.UTF_8)

同样,您可以避免处理受控异常。

字节数组必须有某种编码。如果你有负值,编码就不能是ASCII。一旦你弄清楚了,你可以使用以下方法将一组字节转换为字符串:

byte[] bytes = {...}
String str = new String(bytes, StandardCharsets.UTF_8); // for UTF-8 encoding

你可以使用很多编码,看看Oracle javadocs中支持的编码。