-3

I have a string array of form:

String[] s = {0x22, 0xD2, 0x01}

Now I have to convert it to byte array form like:

byte[] bytes = {(byte)0x22, (byte)0xD2, (byte)0x01}

It can be done in single line in c# but how to do it in Java as I have to append bytes array to another array of same kind and format.

Here I have included some part of the code as I can't include whole code:

String sr = "22D201";
String[] s = {sr.substring(0, 2),sr.substring(2, 4),sr.substring(4)};
byte[] ret = new byte[]{(byte)0x2C, (byte)0x04, (byte)0x01, (byte)0x67, (byte)0x00, (byte)0x00, (byte)0x3D};

Now I have to append byte[] bytes to byte[] ret but I can't as array is in the form of String that is String[] s. So how to covert String[] s so that I can add it to byte[] ret.

  • 3
    This `String[] s = {0x22, 0xAC, 0xFF};` is not valid Java: "incompatible types: int can not be converted to String". Plus, `AC` and `FF` are to large for a byte. –  May 20 '15 at 08:54
  • Plese [edit] your question and include your real code. –  May 20 '15 at 08:57
  • Hey guys thanks and I got this. I used this method and it's working. `public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)+Character.digit(s.charAt(i+1), 16)); } return data; }` – shivam bajpai May 20 '15 at 11:33

1 Answers1

0

You can use String.getBytes();.

You can also initialize a String using a byte array and a specified encoding scheme:

String s = new String(new byte[]{ /* Bytes data. */}, "UTF-8");

For an array of Strings, each individual String's byte array could therefore be processed as follows:

for(final String s : lStrings) {
     byte[] lBytes = s.getBytes();
}

If you wanted to make a contiguous array of these types, you could use a ByteArrayOutputStream.

ByteArrayOutputStream b = new ByteArrayOutputStream();
for(final String s : lStrings) {
    b.write(s.getBytes());
}
final byte[] lTotalBytes = b.toByteArray();
/* Make sure all the bytes are written. */
b.flush();
/* Close the stream once we're finished. */
b.close();
Mapsy
  • 4,192
  • 1
  • 37
  • 43