I have a string that looks like this: ["1011000", "1000010", "1001101", "1000011"].
My argument is coming from elsewhere so it needs to be this way.
I need to typecast this to a real byte array.
Here's my method:
public void send(String[] payloadarr) throws IOException {
byte [] payload = {};
for (int i = 0; i < payloadarr.length; i++) {
byte x = (byte) payloadarr[i];
payload[i] = x;
}
//do byte stuff with payload
}
It doesn't work, however. Complains about inconvertable types String to byte.
Can anyone help me with this typecasting?
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
Given a Byte value in Java, the task is to convert this byte value to string type. One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.
A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..
EDITED: Thanks to @Gabe for idea to change from Integer.parseInt
to Byte.parseByte
You can use Byte.parseByte(String s, int radix) - your radix being 2
(ie base 2)
Here's a handy method to convert an array of String to byte[]
:
public static byte[] stringsToBytes(String[] payloadarr) {
byte[] payload = new byte[payloadarr.length];
for (int i = 0; i < payloadarr.length; i++) {
payload[i] = Byte.parseByte(payloadarr[i], 2);
}
return payload;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(stringsToBytes(new String[] { "1011000", "1000010", "1001101", "1000011" })));
}
Output:
[88, 66, 77, 67]
It's hard to tell from your question, but it sounds like you really want
byte x = Byte.parseByte(payloadarr[i], 2);
You can't do this using (just) type casts.
You need to use Integer.parseInt(String, int)
where the int
is 2. That will give you an int
which you need to cast to a byte
.
public void send(String[] payloadarr) throws IOException {
byte [] payload = new byte[payloadarr.length];
for (int i = 0; i < payloadarr.length; i++) {
payload[i] = (byte) Integer.parseInt(payloadarr[i], 2);
}
//do byte stuff with payload
}
Notes
The above method will throw NumberFormatException
if any of the components of payloadarr
is not a binary string.
I fixed the initialization of payload
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With