How to convert Java String into byte[]?

后端 未结 8 1474
不知归路
不知归路 2020-11-22 16:00

Is there any way to convert Java String to a byte[] (not the boxed Byte[])?

In trying this:

System.ou         


        
相关标签:
8条回答
  • 2020-11-22 16:30

    You can use String.getBytes() which returns the byte[] array.

    0 讨论(0)
  • 2020-11-22 16:40

    I know I'm a little late tothe party but thisworks pretty neat (our professor gave it to us)

    public static byte[] asBytes (String s) {                   
               String tmp;
               byte[] b = new byte[s.length() / 2];
               int i;
               for (i = 0; i < s.length() / 2; i++) {
                 tmp = s.substring(i * 2, i * 2 + 2);
                 b[i] = (byte)(Integer.parseInt(tmp, 16) & 0xff);
               }
               return b;                                            //return bytes
        }
    
    0 讨论(0)
提交回复
热议问题