将一组字符串转换为byte []数组 [英] Converting a set of strings to a byte[] array
问题描述
我正在尝试将一组字符串转换为byte []数组.首先,我要做这样的事情将字节数组转换为字符串:
I am tring to convert a set of strings to a byte[] array. At first, I do something like this to convert a byte array to a string:
public String convertByte(byte[] msg) {
String str = "";
for(int i = 0; i < msg.length; i++) {
str += (msg[i] + " * ");
}
return str;
}
当我尝试转换回byte []数组时,得到的值与转换为String时的值不同.我最初有一些东西给了我不正确的值.
When I try to convert back to the byte[] array, I don't get the same values as the ones when converted to a String. I originally had something gave me incorrect values.
我目前正在尝试以下方法:
I am currently trying something along the lines of:
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()方法,它将返回一个字节数组而不是一个字节,这是我的问题.
If I try to use the getbytes() method from the String api, It returns a byte array rather than a byte and this is my problem.
任何帮助将不胜感激.
推荐答案
这应该有效:
This should work:
byte[] bytes = "Hello World".getBytes("UTF-8");
String hello = new String(bytes, "UTF-8");
以上示例使用UTF-8编码,仅作为示例.在消息输入中使用您期望的字符编码.(此答案"不是问题的答案...)
The above example uses the UTF-8 encoding and just serves as an example. Use the character encoding you expect in your message input. (This 'answer' wasn't an answer to the question...)
修改
因此,我们需要从byte []到String并再返回到byte []的转换. me123在值之间(和前面)添加了定界符.正如其他人已经解释的那样,
1.拆分的正则表达式必须为" \\* "
并且
2.魔术方法是Byte.parseByte(st[i])
So we need a conversion from byte[] to String and back to byte[]. me123 added delimiters between the (and in front of) the values. As others already explained,
1. the regexp for the split has to be " \\* "
and
2. the magic method is Byte.parseByte(st[i])
这是不使用定界符的替代方法,但修复了字节条目的宽度. StringToByte转换器仅基于字符串char数组显示了一种非常快速的解决方案.
Here is an alternative without using a delimiter but a fixes width for the byte entries. The StringToByte converter shows a pretty fast solution just based on the strings char array.
public static String convertByte(byte[] msg) {
StringBuilder sb = new StringBuilder();
for (byte b:msg) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
public static byte[] convertStr(String ln)
{
System.out.println(ln);
char[] chars = ln.toCharArray();
byte[] result = new byte[ln.length()/2];
for (int i = 0;i < result.length; i++) {
result[i] = (byte) hexToInt(chars[2*i], chars[2*i+1]);
}
return result;
}
private static int hexToInt(char c1, char c2) {
return ((c1 <= '9' ? c1 - '0':c1 - 'a'+10) << 4)
+ (c2 <= '9' ? c2 - '0':c2 - 'a'+10);
}
这篇关于将一组字符串转换为byte []数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!