将byte []转换为String并通过charset更改还原的机制是什么

时间:2016-07-01 13:51:12

标签: java string character-encoding byte

有一个简单的问题,并且很容易理解代码的含义:
 public class TestByteArrayConvertString {

    public static void main(String args[]) throws UnsupportedEncodingException {        
        byte[] b1 = {-11, -73, -51, 52, -75, 75, -122, 86, -60, -48, 52, -85, 98, 16, -108, -124};
        byte[] b2 = {20, -56, 16, -94, -119, -48, -22, 84, -39, 35, -10, -49, -37, -28, 7, -44};
        byte[] b3 = {'t','e','s','t'};
        System.out.println(getCharsetForByteArray(b1));
        System.out.println(getCharsetForByteArray(b2));
        System.out.println(getCharsetForByteArray(b3));     
    }

    public static String getCharsetForByteArray(byte[] bytes) {
        UniversalDetector ud = new UniversalDetector(null);
        ud.handleData(bytes, 0, bytes.length);
        ud.dataEnd();
//      ud.reset();
        return ud.getDetectedCharset();
    }   
}

另外,我使用juniversalchardet api来了解charset与byte []一起使用的内容。 您能否知道上述代码的结果?结果真是太可惜了:

WINDOWS-1252
null
null

注意,b1和b2的值都是从sublime中的相同txt复制的,而b3是在Eclipse中正确输入的(Java编码是UTF-8)。 最后,我有一些困惑的问题,将byte []转换为String或revert,主要是因为它们的charset !!!

好的,真正的问题是:

public static String md5Encrypt(String encryptStr) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(encryptStr.getBytes("utf8"));
            byte[] bs = md5.digest();
            System.out.println("length1 :" + bs.length);
            String str = new String(bs);
            System.out.println("length2 :" + str.getBytes("utf8").length);
            return str;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

当我将“test”作为参数调用md5Encrypt方法时,得到以下混淆结果:

length1 :16
length2 :32

我花了很多时间在上面:(

0 个答案:

没有答案