byte和String的互相转换

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

再把转换出来的byte[]转回String,看下和原来数据是否是一样的:

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[]转String,同时设置格式,根据实际情况选择合适的格式

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
    }
}
发布了166 篇原创文章 · 获赞 155 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_38106322/article/details/104237353