0

There is a simply problem,and easily understand the code what it is mean:

 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();
    }   
}

Additional,I use juniversalchardet api to know what the charset is using with the byte[]. Could you know the result of the above code? It is really suprise for the result is :

WINDOWS-1252
null
null

Note that,the value of b1 and b2 are both copyed from the same txt in sublime,and b3 is dierectly entered in Eclipse(The Java encoding is UTF-8). Finally,I have some confused problems with converting byte[] to String or revert,mainly cause the charset of them!!!

Ok,the real problem is follow:

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

When I take "test" as parameter to invoke md5Encrypt method,get the follow confused result:

length1 :16
length2 :32

I hava spent much time on it :(

Community
  • 1
  • 1
nolan4954
  • 111
  • 1
  • 9
  • 1
    You are confused about auto-detecting the charset, or about how to read into a java String and out into another format? – ControlAltDel Jul 01 '16 at 13:56
  • I'm sorry. I'm much confused about that byte[] converting String and String converting to byte[] will change the value of byte[].You can see my real problem added at the end of question.thx. – nolan4954 Jul 01 '16 at 14:22

0 Answers0