[英]Java: Converting byte string to byte array
我想将我的byte[]
转换为String
,然后将该String
转换为byte[]
。
所以,
byte[] b = myFunction();
String bstring = b.toString();
/* Here the methode to convert the bstring to byte[], and call it ser */
String deser = new String(ser);
bstring 给了我[B@74e752bb
。
然后将String
转换为byte[]
。 我没有按这个顺序使用它,但这是一个例子。
我需要如何在 Java 中执行此操作?
将 byte[] 转换为 String 时,您应该使用它,
new String(b, "UTF-8");
代替,
b.toString();
将字节数组转换为字符串时,应始终指定字符编码并在从字符串转换回字节数组时使用相同的编码。 最好是使用 UTF-8 编码,因为它是非常强大和紧凑的编码,可以表示超过一百万个字符。 如果不指定字符编码,则可能会使用平台的默认编码,当从字节数组转换为字符串时,可能无法正确表示所有字符。
你的方法处理得当,应该写成这样,
public static void main(String args[]) throws Exception {
byte[] b = myFunction();
// String bstring = b.toString(); // don't do this
String bstring = new String(b, "UTF-8");
byte[] ser = bstring.getBytes("UTF-8");
/* Here the methode to convert the bstring to byte[], and call it ser */
String deser = new String(ser, "UTF-8");
}
我不是专家,但您应该尝试“Byte”类提供的方法,并在必要时尝试一些循环。 尝试byte b = Byte.parseByte(String s)
将字符串转换为字节和String s = Byte.toString(byte b)
将字节转换为字符串。 希望这可以帮助 :)。
你可以这样做,
String string = "Your String";
byte[] bytesFromString = string.getBytes(); // get bytes from a String
String StringFromByteArray = new String(bytesFromString); // get the String from a byte array
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.