String of byte and mutual conversion

byte转String

public class TestMain {
    public static void main(String[] args) throws Exception {
        Byte a = 36;
        String b = a.toString();
        System.out.println(b);//输出结果:36
    }
}

String转byte[]

public class TestMain {
    public static void main(String[] args) throws Exception {
        String test = "666";
        byte[] bytes = test.getBytes();
        System.out.println(bytes);//输出结果:[B@67117f44
    }
}

byte[]转String

Then converted out of the byte [] back to String, and look at whether the original data is the same:

public class TestMain {
    public static void main(String[] args) throws Exception {
        String test = "666";
        byte[] bytes = test.getBytes();
        System.out.println(bytes);//输出结果:[B@67117f44
        String test1 = new String(bytes);
        System.out.println(test1);//输出结果:666
    }
}

byte [] turn String, and set format, select a suitable format according to the actual situation

public class TestMain {
    public static void main(String[] args) throws Exception {
        String test = "666";
        byte[] bytes = test.getBytes();
        System.out.println(bytes);//输出结果:[B@67117f44
        String test1 = new String(bytes, "UTF-8");
        System.out.println(test1);//输出结果:666
    }
}
Published 166 original articles · won praise 155 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_38106322/article/details/104237353