1

I want to split each of two chars in string and convert it to hex byte array representation, i am just lost how to do this.

in string a= hex a which is 10 in decimal in string b= hex b which is 11 in decimal

String toConvert = "abbbbbbbbbbbbbbbbbbbbbbc";
byte[] output = new byte[12];





                          Input
 ab    bb   bb    bb  bb   bb   bb   bb   bb   bb   bb   bc
                          output
[-85, -69, -69, -69, -69, -69, -69, -69, -69, -69, -69, -68]
H4SN
  • 1,482
  • 3
  • 24
  • 43
  • no i want a byte array ass output not string and its string to hex not hex to string. – H4SN Nov 22 '14 at 15:09
  • You reserved 12 bytes for a 24 charackter string? – greenapps Nov 22 '14 at 15:13
  • http://stackoverflow.com/questions/5886619/hexadecimal-to-integer-in-java – code monkey Nov 22 '14 at 15:16
  • example (ab) a is msb and b is lsb i want to combine them and make a 16bit no than convert it to hex – H4SN Nov 22 '14 at 15:18
  • 1
    `in string a= hex a which is 10 in decimal in string b= hex b which is 11 in decimal` You mean in `String toConvert`? What a terrible example! Better `String toConvert = "0344A7DF";`. And you will not convert to hex but decode from hex representation. – greenapps Nov 22 '14 at 15:24

3 Answers3

1

Takes the first character in a group of two, multiplies its hex value by 16 (it's in the 161 place). That result is added to the second character's hex value.

String toConvert = "abbbbbbbbbbbbbbbbbbbbbbc";
byte[] output = new byte[toConvert.length() / 2];

for (int i = 0; i < output.length; i++) {
    output[i] |= Character.digit(toConvert.charAt(i * 2), 16) * 16;
    output[i] |= Character.digit(toConvert.charAt(i * 2 + 1), 16);
}
August
  • 12,410
  • 3
  • 35
  • 51
0

Apache Common Codec's Hex class does exactly what you need:

byte[] bytes = Hex.decodeHex("abbbbbbbbbbbbbbbbbbbbbbc".toCharArray());

If you can't/won't use third parties, you can always "borrow" their implementation (slightly simplified - I omitted correctness checks for simplicity):

public static byte[] decodeHex(final char[] data) {

  final int len = data.length;

  // Handle empty string - omitted for clarity's sake

  final byte[] out = new byte[len >> 1];

  // two characters form the hex value.
  for (int i = 0, j = 0; j < len; i++) {
      int f =  Character.digit(data[j], 16) << 4;
      j++;
      f = f | Character.digit(data[j], 16);
      j++;
      out[i] = (byte) (f & 0xFF);
  }

  return out;
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0
for(int i = 0; i < 12; i++) {
    output[i] = (byte) Integer.parseInt(toConvert.substring(i*2, i*2+2), 16);
}
Dima
  • 39,570
  • 6
  • 44
  • 70