15,849,180 members
1.00/5 (1 vote)
See more:
For eg: String a="12345678abcdefgh";
This string should be converted to a byte array in android...like 0x12 0x34 0x56 0x78 0xab 0xcd 0xef 0xgh...................
pls help urgent..........
Posted
Updated 28-Oct-14 5:48am
v2
Alan N 28-Oct-14 10:55am
Well, that's going to be tricky! If you could explain what value you mean by 0xgh someone may be able to answer.
User1454 28-Oct-14 11:03am
sir,....actually........ value of "a" should be converted to byte array
byte[] command={0x2D,0x12,0x01,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x02 ,(byte) 0xFF ,(byte) 0xFF ,0x08 ,0x00 ,0x06 ,0x11 ,0x01 ,0x02};

so this value i will be sending using tcp/ip socket....
Dilan Shaminda 28-Oct-14 11:10am
string can be converted to byte array in android by byte[] bytes = a.getBytes(Charsets.UTF_8); what do you mean by 0x12 0x34 0x56 0x78 0xab 0xcd 0xef 0xgh..... ?
User1454 28-Oct-14 11:13am
I need byte array from hex string.................
Dilan Shaminda 28-Oct-14 11:17am

## Solution 1

From this hex String To Byte Array tutorial

Java
```public static byte[] hexStringToByteArray(String s) {
byte[] b = new byte[s.length() / 2];
for (int i = 0; i < b.length; i++) {
int index = i * 2;
int v = Integer.parseInt(s.substring(index, index + 2), 16);
b[i] = (byte) v;
}
return b;
}
```

User1454 28-Oct-14 11:21am
thank u so much thats working ..............and this is what i need..... u saved my time...
Dilan Shaminda 28-Oct-14 11:21am
you are welcome :-)