[英]Need to help to convert string to hex bytes
I am programming in Java. 我正在用Java编程。 The program have a String as below.
该程序具有如下字符串。
String str = "byte."
Can the above string be converted to an array of hex bytes as below? 可以将上述字符串转换为如下所示的十六进制字节数组吗?
byte[] data = {0x62, 0x79, 0x74, 0x65};
Thank you. 谢谢。
There's no such thing as "hex bytes" and more than there are "decimal integers" vs "hex integers". 没有“十六进制字节”之类的东西,还有“十进制整数” vs“十六进制整数”之类的东西。
You can certainly convert a string to a byte array though. 您当然可以将字符串转换为字节数组。 For example:
例如:
byte[] data = str.getBytes("UTF-8");
The UTF-8
part here is the name of the encoding to use - where an encoding is effectively a mapping between Unicode characters and bytes. 这里的
UTF-8
部分是要使用的编码的名称- 编码实际上是Unicode字符和字节之间的映射。 (It's somewhat more complicated than that, but it's a good first approximation.) (这比这要复杂一些,但这是一个很好的第一近似值。)
There is a parameterless overload of String.getBytes()
but I would strongly recommend that you don't use it - it will pick the platform default encoding, which is rarely a good idea. 有一个参数的超载
String.getBytes()
但我会强烈建议您不要使用它-它会选择平台默认的编码,这是很少一个好主意。
You can also use an overload taking a Charset
, which ends up being nicer in conjunction with a library such as Guava , where you can write: 您还可以使用带有
Charset
的重载,将其与Guava之类的库结合起来会更好,您可以在其中编写:
byte[] data = str.getBytes(Charsets.UTF_8);
... so you no longer rely on a string representation. ...因此您不再依赖字符串表示形式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.