Reputation: 281
I'm trying to convert specific String to a byte[].
The String looks like: 55 55 F5 FF FF
and here is the method I wrote for it, hope someone can tell me what is wrong or has a better solution.
public static byte[] stringToByte(String text) {
//byte[] length ==> String (length+1)/3
byte raw[] = new byte[(text.length() + 1) / 3];
int j = 0;
for (int i = 0; i < text.length(); i += 2) {
String h = "";
h += text.charAt(i);
h += text.charAt(i + 1);
i++;
raw[j] = Byte.valueOf(h);
j++;
}
return raw;
}
The problem is it works until it comes to F5.
I need the same values in the byte[] as if I use
byte raw[] = {(byte) 0x55, (byte) 0x55, (byte) 0x5F,(byte) 0xFF,(byte) 0xFF};
Upvotes: 1
Views: 2393
Reputation: 42020
You could also use StringTokenizer
for each token.
public static byte[] stringToByte(String text) {
StringTokenizer st = new StringTokenizer(text);
byte raw[] = new byte[st.countTokens()];
for (int i = 0; i < raw.length; i++) {
raw[i] = (byte) Integer.parseInt(st.nextToken(), 16);
}
return raw;
}
Upvotes: 0
Reputation: 200148
This will work:
public static byte[] stringToByte(String text) {
final String[] split = text.split("\\s+");
final byte[] result = new byte[split.length];
int i = 0;
for (String b : split) result[i++] = (byte)Integer.parseInt(b, 16);
return result;
}
Why? byte
is a signed quantity and you cannot parse anything out of its range directly into byte
. But if you parse an int
and then use a narrowing conversion into byte
, you'll get your result.
Upvotes: 2
Reputation: 2804
byte[] raw = new byte[text.length() >> 1];
for(int i=0; i<text.length();i+=2){
raw[i >> 1] = Integer.parseInt(text.substring(i, i+2),16);
}
I used Integer.parseInt()
instead of Byte.parseByte()
because Byte is not unsigned byte. I tried it with String text = "55555FFF";
.
Upvotes: 0
Reputation: 7215
It looks like you're just looping through a space delimited String and parsing out Byte objects. In the case, I'd suggest using something like:
String text = "";
String[] strArr = text.split(" ");
for (String str: strArr)
{
//convert string to byte here
}
Upvotes: 0