Converting a set of strings to a byte[] array

前端 未结 6 1022
甜味超标
甜味超标 2021-01-23 04:45

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[         


        
6条回答
  •  情话喂你
    2021-01-23 05:40

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

提交回复
热议问题