我必须将字节数组转换为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);

我被这个问题难住了。


当前回答

这个对我来说适用于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);
}

其他回答

虽然base64编码是安全的,有人可能会争论“正确的答案”,但我在这里寻找一种方法来将Java字节数组转换为Java字符串。也就是说,字节数组的每个成员在其对应的String中保持完整,不需要额外的空间用于编码/传输。

这个描述8位透明编码的答案对我很有帮助。我在二进制数据上使用ISO-8859-1来成功地来回转换(二进制<->字符串),而没有base64编码所需的膨胀空间要求,因此对我的用例YMMV是安全的。

这也有助于解释何时/是否应该进行实验。

我们只需要用数组:http://www.mkyong.com/java/how-do-convert-byte-array-to-string-in-java/构造一个新的String

String s = new String(bytes);

结果字符串的字节数取决于所使用的字符集。new String(bytes)和new String(bytes, charset . forname ("utf-8"))和new String(bytes, charset . forname ("utf-16"))在调用String#getBytes()时都将有不同的字节数组(取决于默认字符集)

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

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

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

字符串是char's (16bit unsigned)的集合。所以如果你要把负数转换成字符串,它们会在转换中丢失。

private static String toHexadecimal(byte[] digest){
        String hash = "";
    for(byte aux : digest) {
        int b = aux & 0xff;
        if (Integer.toHexString(b).length() == 1) hash += "0";
        hash += Integer.toHexString(b);
    }
    return hash;
}