Reputation: 47
I'm trying to convert a String to a byte array which has 2 different bytes.
for eg: String s1 = " 055E"
I need to convert this into like
byte b1 = Integer.parseInt(05,16); - 1byte
byte b2 = Integer.parseInt(5E,16); - 1byte
At the end i need to have a byte array which will have values b1, b2.
byte[] b = {b1, b2};
Any help on this would be appreciated. thanks in advance
Upvotes: 0
Views: 175
Reputation: 36456
First allocate enough memory for the array. Then loop through every pair of characters and convert them to a byte. Store the result in the array.
s = s.trim();
byte[] b = new byte[s.length()/2];
for(int i = 0; i < s.length(); i+= 2) {
b[i/2] = Byte.parseByte(s.substring(i,i+2),16);
}
Upvotes: -1
Reputation: 234795
Try this:
String s1 = " 055E";
s1 = s1.trim();
byte[] b = {
(byte) Integer.parseInt(s1.substring(0, 2), 16),
(byte) Integer.parseInt(s1,substring(2), 16)
}
Upvotes: 2