如何将字符串转换为字节数组? [英] How to cast String to byte array?

查看:171
本文介绍了如何将字符串转换为字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个String,它包含字节数组的String值。
我如何将这个字符串转换为字节数组?
我如何尝试:

I have a String, which contains the byte array's String value. How could I convert this String to byte array? How I tried:

String stringValue="33321232"; //the bytes in String
byte[] bytes= (byte[])stringValue;
System.out.println(getByteArrayAsString(bytes));

getByteArrayAsString 方法应返回结果字符串: 33321232 ,所以同样是 stringValue 。 (这是我的方法,它是工作,但如何获得字节?)

The getByteArrayAsString method should give back the result String: 33321232, so the same which is the stringValue. (This is my method, it is works, but how to get the bytes?)

谢谢! / p>

Thank you!

推荐答案


我有一个String,其中包含字节数组的String值。 $ b

I have a String, which contains the byte array's String value.

这还不清楚。如果你已经将二进制数据转换为文本,你怎么做的?这应该指导你如何转换回来。例如,如果您已经开始使用任意二进制数据(例如某种形式的图像),那么通常您希望使用base64或hex转换为字符串。

This is unclear to start with. If you've converted binary data to text, how have you done that? That should guide you as to how you convert back. For example, if you've started with arbitrary binary data (e.g. an image in some form) then typically you'd want to convert to a string using base64 or hex. If you started with text data, that's a different matter.

字符串不是一个字节数组,这就是为什么铸造失败。对于基本上是文本的数据,需要在二进制和文本之间转换,应用编码(在Java中也被称为charset)。

A string isn't a byte array, which is why the cast fails. For data which is fundamentally text, need to convert between binary and text, applying an encoding (also known somewhat confusingly as a charset in Java).

其他答案建议使用 new String(byte []) String.getBytes()。我强烈建议您使用这些成员

Other answers have suggested using new String(byte[]) and String.getBytes(). I would strongly recommend against using those members - use the ones which specify an encoding instead:

new String(byte[], String) // the string argument is the charset
new String(byte[], Charset) 

String.getBytes(String) // the string argument is the charset
String.getBytes(Charset)

如果不指定编码将使用平台默认编码,这通常不是你想要的。您需要考虑使用哪种编码。

If you don't specify an encoding, it will use the platform default encoding, which is often not what you want. You need to consider which encoding you want to use.

使用 Charset 指定编码比清除使用字符串 - 值得注意的是 StandardCharsets 如果您使用的是Java 7,例如

Using a Charset to specify the encoding is cleaner than just using the string - it's worth being aware of StandardCharsets if you're using Java 7, e.g.

byte[] bytes = stringValue.getBytes(StandardCharsets.UTF_8);
System.out.println(new String(bytes, StandardCharsets.UTF_8);

这篇关于如何将字符串转换为字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆