有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将32字节数组转换为32位字符串

我有以下代码。我有一个32长度的字符串,它被转换成字节数组。问题是我需要将其转换为32长度的字符串。问题是,它以64长度字符串的形式返回。我该看看什么魔法吗

class Go {

    public void run() {
        String testString = "12345678901234567890123456789012";

        byte[] bytesData = testString.getBytes();
        StringBuilder st = new StringBuilder();

        for (byte b : bytesData) {
            st.append(String.format("%2d", b));
        }

        System.out.println(st.toString());
    }


    public static void main(String[] v2) {
        Go v = new Go();
        v.run();
    }
}

共 (2) 个答案

  1. # 1 楼答案

    @azro给了你正确的答案,但为了教育起见,我会指出你做错了什么。当你得到字符串中charbyte值时,你得到的是ascii值。所以当你使用String.format("%2d", b)时,你得到的是char本身的int值,而不是它所代表的char。相反,您可以将循环更改为以下内容:

        for (byte b : bytesData) {
            st.append( (char)b );
        }
    

    不过,还是要用@azro说的话。我只是解释一下,如果你对引擎盖下的工作方式感兴趣,你可以怎么做

  2. # 2 楼答案

    您使用这个String构造函数:public String(byte[] bytes)Oracle Doc

    String testString = "12345678901234567890123456789012";
    System.out.println(testString);                          //12345678901234567890123456789012
    
    byte[] bytesData = testString.getBytes();
    
    String res = new String(bytesData);
    System.out.println(res);                                 //12345678901234567890123456789012