如何将字符串转换为字节并返回

发布于 2024-12-04 17:24:20 字数 190 浏览 0 评论 0原文

为了转换字符串,我将其转换为字节,如下所示: byte[] nameByteArray = cityName.getBytes();

为了转换回来,我做了: String returnedString = new String(nameByteArray); 这显然不起作用。我该如何将其转换回来?

For converting a string, I am converting it into a byte as follows:
byte[] nameByteArray = cityName.getBytes();

To convert back, I did: String retrievedString = new String(nameByteArray); which obviously doesn't work. How would I convert it back?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

能否归途做我良人 2024-12-11 17:24:20

您原来的城市名称中有哪些字符?尝试这样的 UTF-8 版本:

byte[] nameByteArray = cityName.getBytes("UTF-8");
String retrievedString = new String(nameByteArray, "UTF-8");

What characters are there in your original city name? Try UTF-8 version like this:

byte[] nameByteArray = cityName.getBytes("UTF-8");
String retrievedString = new String(nameByteArray, "UTF-8");
痴梦一场 2024-12-11 17:24:20

这显然不起作用。

事实上,你就是这样做的。唯一可能出错的地方是您隐式使用平台默认编码,该编码在系统之间可能有所不同,并且可能无法表示字符串中的所有字符。

解决方案是显式使用可以表示所有字符的编码,例如 UTF-8:

byte[] nameByteArray = cityName.getBytes("UTF-8");

String retrievedString = new String(nameByteArray, "UTF-8");

which obviously doesn't work.

Actually that's exactly how you do it. The only thing that can go wrong is that you're implicitly using the platform default encoding, which could differ between systems, and might not be able to represent all characters in the string.

The solution is to explicitly use an encoding that can represent all characts, such as UTF-8:

byte[] nameByteArray = cityName.getBytes("UTF-8");

String retrievedString = new String(nameByteArray, "UTF-8");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文