Reputation: 95
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?
Upvotes: 5
Views: 263
Reputation: 424983
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]
Upvotes: 6
Reputation: 718718
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
...
Upvotes: 2
Reputation: 86708
It's hard to tell from your question, but it sounds like you really want
byte x = Byte.parseByte(payloadarr[i], 2);
Upvotes: 3