Converting a set of strings to a byte[] array

2019-02-27 04:10发布

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;
}

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;
}

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.

Any help would be much appreciated.

6条回答
兄弟一词,经得起流年.
2楼-- · 2019-02-27 04:35

This should work:

byte[] bytes = "Hello World".getBytes("UTF-8");
String hello = new String(bytes, "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...)

Edit

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])

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);
}
查看更多
Root(大扎)
3楼-- · 2019-02-27 04:36

If you are sure that the string contains 1 byte, you can do:

byteArray[i] = st[i].getbytes()[0];
查看更多
老娘就宠你
4楼-- · 2019-02-27 04:49

I don't understand why you are trying to get those bytes by characters. getBytes() and its variants will give you a byte[] array for whole string at once. However, if you want to see how characters are encoded, your approach my be good, but you have to keep in mind, that one character could be encoded in e.g. one to four bytes in some encodings, thus you need a byte array for every character.

查看更多
冷血范
5楼-- · 2019-02-27 04:51

If you are certain the String will be small enough to fit in one byte, you could do

st[i].getBytes()[0];

however, in most of the cases, your String will probably be bigger, so in these cases it is not possible...

查看更多
【Aperson】
6楼-- · 2019-02-27 04:56

Using Byte.parseByte may help making your second snippet work.

But, unless you have some specific reason to use that kind of representation, I'd encode strings to byte arrays using the Java methods mentioned in other answers.

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;
}
查看更多
倾城 Initia
7楼-- · 2019-02-27 05:00

hexToInt should be like this

private static int hexToInt(char c1, char c2) {
    return (Character.digit(c1, 16) << 4) + Character.digit(c2, 16);
}

Otherwise CA returns AA in byte.

查看更多
登录 后发表回答