1

我需要从字符串转换为相同的字节数组:

String data = request.getParameter("data");

byte[] dataByte = new byte[]{};

data = -60,-33,-10,-119,126,114,-61,-31,55,-102,-35,-72,114,77,115,72,79,-117,102,64,98,-20,-75,27,58,-59,86,-97,106,19,-112,-79,100,105,115,107,100,105,114,101,99,116,111,114,95,115,97,102,101,46,99,111,110,102,105,103,49,52,53,53,83,112,97,99,101,115,83,116,111,114,101,114,117,99,111,110,116,101,110,116,85,114,108,61,115,116,111,114,101,58,47,47,50,48,49,50,47,49,48,47,49,47,57,47,53,50,47,57,100,48,48,48,48,55,97,45,54,50,48,48,45,52,54,52,102,45,97,48,48,97,45,50,52,97,100,52,98,100,55,50,53,53,48,46,98,105,110,124,109,105,109,101,116,121,112,101,61,97,112,112,108,105,99,97,116,105,111,110,47,111,99,116,101,116,45,115,116,114,101,97,109,124,115,105,122,101,61,52,53,57,53,49,124,101,110,99,111,100,105,110,103,61,85,84,70,45,56,124,108,111,99,97,108,101,61,114,117,95,124,105,100,61,52,49,48,56,101,57,100,100,50,100,56,45,56,102,54,97,45,52,54,55,54,45,56,53,99,57,45,50,52,54,102,55,57,57,55,101,102,48,99,77,111,110,32,79,99,116,32,48,49,32,48,57,58,53,50,58,49,53,32,78,79,86,83,84,32,50,48,49,50,119,111,114,107,115,112,97,99,101,97,100,109,105,110,97,100,109,105,110
4

5 回答 5

2
String[] dataArray = data.split(",")

然后,您可以对其进行迭代,dataArray然后从中创建byte[]

    String dataArray[] = data.split(",");
    byte[] bytes = new byte[dataArray.length];
    int count = 0;
    for(String str : dataArray)
    {
        bytes[count++] = Byte.parseByte(str);
    }

如果您知道字符编码,那么您可以使用#String.getBytes

于 2012-10-09T10:40:29.990 回答
0

String.getBytes(String charsetName)会给你一个字节数组。你将不得不小心重新。指定您的字符编码。

于 2012-10-09T10:41:19.507 回答
0

使用 StringTokenizer 或 String.split() 方法并将每个子字符串解析为字节。注意编码。

于 2012-10-09T10:41:31.067 回答
0

使用String.split()并遍历结果数组:

String[] array = data.split(",");
byte[] dataByte = new byte[ array.length ];
for ( int i=0 ; i<array.length ; i++ ) { dataByte[ i ] = Byte.parseByte( array[ i ] ); }

干杯,

于 2012-10-09T10:43:53.283 回答
0

您可以为此目的使用String#getBytes()方法:-

String data = request.getParameter("data");
byte[] dataByte = data.getBytes()

它使用default character encoding..你可以指定你自己的..

请参见String#getBytes(Charset)

或者您可以在拆分字符串数组的每个值后使用Byte#parseByte(String)方法:-

    String data = request.getParameter("data");
    String arr[] = data.split(",");
    byte[] newarr = new byte[arr.length];

    int count = 0;
    for (String val: arr) {
        newarr[count++] = Byte.parseByte(val);
        System.out.println(Byte.parseByte(val) + ", ");
    }
于 2012-10-09T10:44:34.607 回答