且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将字节数组转换为字符串,反之亦然?

更新时间:2022-12-07 17:07:04

您的字节数组必须有一些编码。如果您有负值,则编码不能是ASCII。一旦弄明白,就可以使用以下命令将一组字节转换为字符串:

Your byte array must have some encoding. The encoding cannot be ASCII if you've got negative values. Once you figure that out, you can convert a set of bytes to a String using:

byte[] bytes = {...}
String str = new String(bytes, "UTF-8"); // for UTF-8 encoding

您可以使用一堆编码,查看Charset Sun javadocs 中的类。

There are a bunch of encodings you can use, look at the Charset class in the Sun javadocs.