gpt4 book ai didi

java - 将一组字符串转换为 byte[] 数组

转载 作者:行者123 更新时间:2023-11-30 07:38:17 25 4
gpt4 key购买 nike

我正在尝试将一组字符串转换为 byte[] 数组。起初,我做了类似这样的事情来将字节数组转换为字符串:

public String convertByte(byte[] msg) {
String str = "";
for(int i = 0; i < msg.length; i++) {
str += (msg[i] + " * ");
}
return str;
}

当我尝试转换回 byte[] 数组时,我没有得到与转换为字符串时相同的值。我最初有一些东西给了我不正确的值。

我目前正在尝试以下方法:

public static byte[] convertStr(String ln)
{
System.out.println(ln);

String[] st = ln.split(" * ");
byte[] byteArray = new byte[23];
for(int i = 0; i < st.length; i++)
{
byteArray[i] = st[i].get byte value or something;
}

return byteArray;
}

如果我尝试使用 String api 中的 getbytes() 方法,它会返回一个字节数组而不是一个字节,这就是我的问题。

如有任何帮助,我们将不胜感激。

最佳答案

使用 Byte.parseByte 可能有助于使您的第二个代码段正常工作。

但是,除非您有某些特定原因要使用这种表示形式,否则我会使用其他答案中提到的 Java 方法将字符串编码为字节数组。

public static byte[] convertStr(String ln)
{
System.out.println(ln);

String[] st = ln.split(" * ");
byte[] byteArray = new byte[23];
for(int i = 0; i < st.length; i++)
{
byteArray[i] = Byte.parseByte(st[i]);
}

return byteArray;
}

关于java - 将一组字符串转换为 byte[] 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2057387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com