简体   繁体   中英

Java String to byte

I have a String like this in my Java code.

String my = "16 12 12 -119 102 105 -110 52 -89 80 -122 -68 114 20 -92 -28 -121 38 113 61"

the values separated by " " is integer ( you can see it ).

I can convert the integers to a int array, but I need to convert the int values to a byte array. The value represented by each integer is a byte value.

PS.

String aa[] = U.split(" ");
byte bb[] = new byte[aa.length];

for(int q=0;q<aa.length;q++){
  int v = Integer.parseInt(aa[q]);

  bb[q] = ???????????????????--the code I need to convert the int to a byte

}

You should be able to do:

String[] parts = my.split(" ");
byte[] bytes = new byte[parts.length];

for(int i = 0; i < parts.length; i++) {
  bytes[i] = Byte.parseByte(parts[i]);
}

System.out.println(Arrays.toString(bytes));

[16, 12, 12, -119, 102, 105, -110, 52, -89, 80, -122, -68, 114, 20, -92, -28, -121, 38, 113, 61]

Be sure to look over the API for the Byte class, notably Byte.parseByte() .

Edit: You apparently can do most of my answer except for one line. You can just replace this line:

int v = Integer.parseInt(aa[q]);

with this (there's no need to make it an int first, so just skip it and go right to the byte ):

bb[q] = Byte.parseByte(aa[q]);

Or you could just cast the int you created to a byte , like this:

int v = Integer.parseInt(aa[q]);
bb[q] = (byte)v;

The first thing you do is convert that single String into an array of String s by using the String#split() method, like this:

String[] strArray = my.split(" "); // split by the spaces

Then, create a byte array, which will be the same length as the string array:

byte[] byteArray = new byte[strArray.length];

Then iterate over the String array and add each element of the String array to the byte array. Each time you add a number, you have to parse it to a byte from a String , using the Byte#parseByte(String s) method:

for (int i = 0; i < byteArray.length; i++) {
    byteArray[i] = Byte.parseByte(strArray[i]);
}

And then you should have your byte array.

You can split the string and parse each individual String token as Byte :-

String my = "16 12 12 -119 102 105 -110 52 -89 80 -122 -68 114 20 -92 -28 -121 38 113 61";
String [] ints = my.split (" ");
byte[] bArr=new byte[ints.length];

for(int i=0;i<ints.length;i++){

  bArr[i]=Byte.parseByte(ints[i]);
  System.out.println(bArr[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM